我有一个字符串列表,其中包含用逗号分隔的数字。我想从中创建两个整数列表。那就是:
l=["23,2","11,2","12,7"]
我想做的是:
l1=[23,11,12]
l2=[2,2,7]
我将不胜感激。
答案 0 :(得分:2)
您可以使用zip
:
l=["23,2","11,2","12,7"]
l1, l2 = [list(d) for d in zip(*[[int(i) for i in c.split(',')] for c in l])]
输出:
[23, 11, 12]
[2, 2, 7]
答案 1 :(得分:1)
您是否可以使用zip()
来将其分解为基于逗号的每个,
和map
每个子字符串为int的字符串。
l = ["23,2","11,2","12,7"]
l1, l2 = zip(*[map(int, x.split(',')) for x in l])
# l1 = (23, 11, 12)
# l2 = (2, 2, 7)
答案 2 :(得分:1)
Ajax1234的方式非常Python化,无疑是最好的方式。但是,如果这是该语言的新手,则可能更容易理解。它使用拼接:
from itertools import chain
l=["23,2","11,2","12,7"]
l = [x.split(',') for x in l] #Split list elements by comma.
l = list(chain.from_iterable(l)) #Get rid of tuples.
list1 = l[::2] #Take every even indexed element, including 0.
list2 = l[1::2] #Takes every odd indexed element.
输出:
[23, 11, 12]
[2, 2, 7]
Here是指向可以更好地解释它的人的链接。