我有一个看起来像这样的字符串列表,我需要将每个字符串的第一,第二和第三项添加到整数列表a b和c中
剪裁给我
[['3', '5', '10'], ['2', '8', '15'], ['7', '9', '25'], ['4', '6', '20'], ['9', '12', '50'], ['5', '7', '22'], ['3', '8', '17'], ['6', '9', '24'], ['8', '11', '40'], ['7', '10', '30'], []]
这样
a = [3,2,7,...,7]
b = [5、8、9,...,10]
c = [10,15,...,30]
(也希望这些是整数而不是字符串)
我试图用
cuts[i] = cuts[i].strip(",")
认为这会给我[[3] [5] [10]],这会让我添加一个for循环,但是python告诉我列表没有strip属性
最佳答案
以下是基本形式的列表理解:
data = [['3', '5', '10'], ['2', '8', '15'], ['7', '9', '25'], ['4', '6', '20'],
['9', '12', '50'], ['5', '7', '22'], ['3', '8', '17'], ['6', '9', '24'],
['8', '11', '40'], ['7', '10', '30'], []]
a = [int(x[0]) for x in data if len(x) >= 1]
b = [int(x[1]) for x in data if len(x) >= 2]
c = [int(x[2]) for x in data if len(x) >= 3]
print a
print b
print c
或者,将它们保留在二维列表中:
abc = [[int(x[i]) for x in data if len(x) >= i+1] for i in range(len(data[0]))]
print abc
输出:
[[3, 2, 7, 4, 9, 5, 3, 6, 8, 7],
[5, 8, 9, 6, 12, 7, 8, 9, 11, 10],
[10, 15, 25, 20, 50, 22, 17, 24, 40, 30]]