python: convert “5,4,2,4,1,0” into [[5, 4], [2, 4], [1, 0]]
有没有一种"直接"的方法来转换包含将数字放入[X,Y]整数列表中?
1 2 | # from: '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' # to: [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5]] |
顺便说一句,以下是可行的,但并不简单…此外,可以假定输入str已经过验证,以确保它只包含偶数个被逗号交错的数字。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | num_str = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' numpairs_lst = [] # ends up as [[5, 4], [2, 4], [1, 0], ...] current_num_str = '' # the current num within the str; stop when a comma is found xy_pair = [] # this is one of the [x,y] pairs -> [5, 4] for ix,c in enumerate(num_str): if c == ',': xy_pair.append(int(current_num_str)) current_num_str = '' if len(xy_pair) == 2: numpairs_lst.append(xy_pair) xy_pair = [] else: current_num_str += c # and, take care of last number... xy_pair.append(int(current_num_str)) numpairs_lst.append(xy_pair) |
有一个重要的在线帮助让Python的成语是"简单的"。
第一个使用ZIP(成语)。从Python文件:
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).
这样的应用的例子:
1 2 3 4 | >>> num_str = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' >>> zip(*[iter(num_str.split(","))]*2) [('5', '4'), ('2', '4'), ('1', '0'), ('3', '0'), ('5', '1'), ('3', '3'), ('14', '32'), ('3', '5')] |
元组的每个子帧的长度是2。
如果你想在子元素的长度是不同的。
1 2 3 | >>> zip(*[iter(num_str.split(","))]*4) [('5', '4', '2', '4'), ('1', '0', '3', '0'), ('5', '1', '3', '3'), ('14', '32', '3', '5')] |
第二个列表理解习语。如果你想子元素的列表,包在A的理解:
1 2 3 4 5 6 | >>> [list(t) for t in zip(*[iter(num_str.split(","))]*4)] [['5', '4', '2', '4'], ['1', '0', '3', '0'], ['5', '1', '3', '3'], ['14', '32', '3', '5']] >>> [list(t) for t in zip(*[iter(num_str.split(","))]*2)] [['5', '4'], ['2', '4'], ['1', '0'], ['3', '0'], ['5', '1'], ['3', '3'], ['14', '32'], ['3', '5']] |
任何亚群是不完整的元素将被截断由拉链()。所以如果你的字符串不是一个多2,例如,你将松散的负载元素。
如果你想返回的子元素是不完整的(即,如果你不是一个
1 2 3 4 5 6 7 | >>> l=num_str.split(',') >>> [l[i:i+2] for i in range(0,len(l),2)] [['5', '4'], ['2', '4'], ['1', '0'], ['3', '0'], ['5', '1'], ['3', '3'], ['14', '32'], ['3', '5']] >>> [l[i:i+7] for i in range(0,len(l),7)] [['5', '4', '2', '4', '1', '0', '3'], ['0', '5', '1', '3', '3', '14', '32'], ['3', '5']] |
如果你想每个元素是一个int,你可以适用于其他人,现有在变换:
1 2 3 | >>> nums=[int(x) for x in num_str.split(",")] >>> zip(*[iter(nums)]*2) # etc etc etc |
作为一个尖锐的推出在Python 2.4 +评论,所以,你可以理解为一个列表有一个由发电机
1 2 3 4 | >>> nums=(int(x) for x in num_str.split(",")) >>> zip(nums,nums) [(5, 4), (2, 4), (1, 0), (3, 0), (5, 1), (3, 3), (14, 32), (3, 5)] # or map(list,zip(nums,nums)) for the list of lists version... |
如果你是一个长字符串,和你知道你只需要2元,这是更高效的。
一个选项:
1 2 3 4 | >>> num_str = '5,4,2,4,1,0,3,0,5,1,3,3,4,3,3,5' >>> l = num_str.split(',') >>> zip(l[::2], l[1::2]) [('5', '4'), ('2', '4'), ('1', '0'), ('3', '0'), ('5', '1'), ('3', '3'), ('4', '3'), ('3', '5')] |
参考:
如果你真的想,你可以转换为整数,一个整数的列表:第一个
1 | >>> l = map(int, num_str.split(',')) |
解释:
更新:如果你真的想要的列表,你可以使用一个
1 | >>> xy_list = map(list, xy_list) |
注意:johnsyweb更快的回答是,它似乎不做任何不必要的迭代。但实际的差的大小取决于网站上的列表。
1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/env python from itertools import izip def pairwise(iterable): "s -> (s0,s1), (s2,s3), (s4, s5), ..." a = iter(iterable) return izip(a, a) s = '5,4,2,4,1,0,3,0,5,1,3,3,4,3,3,5' fields = s.split(',') print [[int(x), int(y)] for x,y in pairwise(fields)] |
采取从@马蒂诺的答案我的问题,我已经找到了一个非常接近。
输出:
1 | [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [4, 3], [3, 5]] |
第一,使用
1 | num_list = num_str.split(",") |
然后,转换为整数。
1 | num_list = [int(i) for i in num_list] |
然后,使用
1 2 3 4 5 6 7 | from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) pair_list = grouper(2, num_list) |
当然,你可以压缩成一个单一的本线:如果你是节俭的
1 | pair_list = grouper(2, [int(i) for i in num_str.split(",")] |
1 2 3 4 5 | >>> num_str = '5,4,2,4,1,0,3,0,5,1,3,3,4,3,3,5' >>> inums = iter([int(x) for x in num_str.split(',')]) >>> [[x, inums.next()] for x in inums] [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [4, 3], [3, 5]] >>> |
编辑:"一本最drewk甚至或奇数长度的句柄列表:
1 2 3 4 | >>> f = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' >>> li = [int(n) for n in f.split(',')] >>> [li[i:i+2] for i in range(0, len(li), 2)] [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5], [7]] |
这是更广义函数的块大小不同的作品。如果你需要和appends酒店
1 2 3 4 5 6 7 8 9 10 11 12 13 | def breakup(mylist,chunks): mod = len(mylist) % chunks if mod == 0: ae = [] elif mod == 1: ae = mylist[-1:] else: ae = [tuple(mylist[-mod:])] return zip(*[iter(mylist)]*chunks) + ae num_str = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5' lst = map(int,num_str.split(',')) print breakup(lst,2) |
OUT: [(5, 4), (2, 4), (1, 0), (3, 0), (5, 1), (3, 3), (14, 32), (3, 5)]
blockquote></
1
2
3
4
5
6
7
8
9 #declare the string of numbers
str_nums = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
#zip two lists: the even elements with the odd elements, casting the strings to integers
zip([int(str_nums.split(',')[i]) for i in range(0,len(str_nums.split(',')),2)],[int(str_nums.split(',')[i]) for i in range(1,len(str_nums.split(',')),2)])
"""
Of course you would want to clean this up with some intermediate variables, but one liners like this is why I love Python :)
"""它可能是一个发电机。这是一个表达:发电机
1
2
3 import re
ch = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
genexp = ( map(int,ma.groups()) for ma in re.finditer('(\d+)\s*,\s*(\d+)',ch) )你可以做空(第一部分转换到"1,2,3"〔1,2,3)通过使用功能分:
1 num_list = num_str.split(",")有可能是更容易的方式来获得对互惠生,但我愿意做这样的事:
1
2
3
4
5 xy_pairs = []
for i in range(0, len(num_list), 2):
x = num_list[i]
y = num_list[i + 1]
xy_pairs.append([x, y])因此,因为这是所有列表一个定义的长度(2),你应该使用一个可能的元组:
1 xy_pairs.append((x, y))也许这个吗?
1
2 a ="0,1,2,3,4,5,6,7,8,9".split(",")
[[int(a.pop(0)), int(a.pop(0))] for x in range(len(a)/2)]