Python 跳过列表中的空值
我在追加第一个、第二个、直到n个索引的列表时发现了一个问题。它工作正常,直到我发现嵌套列表中的一个列表有空值/长度不相同 假设我有一个嵌套列表Python 跳过列表中的空值,python,Python,我在追加第一个、第二个、直到n个索引的列表时发现了一个问题。它工作正常,直到我发现嵌套列表中的一个列表有空值/长度不相同 假设我有一个嵌套列表 A = [['1 2 3 4 5'],['9 8 7 6 5 4'],['1'],['3 4 5 6'] new = [] for i in range(0,(len(A))): new.append(A[i][0].split(' ')[2]) # 2 here is the index that i want to take new #
A = [['1 2 3 4 5'],['9 8 7 6 5 4'],['1'],['3 4 5 6']
new = []
for i in range(0,(len(A))):
new.append(A[i][0].split(' ')[2]) # 2 here is the index that i want to take
new
# output
[1,9,1,3] # first index
[2,8,4] # second index supposed to be
[3,7,5] # third index supposed to be
错误为Indexer错误:列表索引超出范围
如何跳过空值或如果索引不存在?您可以使用索引执行以下操作,以检查字符串的长度:
index = 0
for elem in A:
if(len(elem[0])>index):
new.append(elem[0].split(' ')[index])
您可以尝试以下逻辑:
A = [['1 2 3 4 5'],['9 8 7 6 5 4'],['1'],['3 4 5 6']]
max_sub_length = max([len(i[0].split()) for i in A])
new = []
A_ = [ele[0].split() for ele in A]
for i in range(max_sub_length):
tmp = [int(ele[i]) for ele in A_ if len(ele) > i]
new.append(tmp)
print(new)
输出为:
[[1, 9, 1, 3], [2, 8, 4], [3, 7, 5], [4, 6, 6], [5, 5], [4]]
你可以用try和except来做这件事。例如:
A = [['1 2 3 4 5'],['9 8 7 6 5 4'],['1'],['3 4 5 6']]
new = []
for i in range(0,(len(A))):
try:
new.append(A[i][0].split(' ')[2])
except IndexError:
continue
print(new)
# Output: ['3', '7', '5']
使用并卸下None
s:
from itertools import zip_longest
A = [['1 2 3 4 5'],['9 8 7 6 5 4'],['1'],['3 4 5 6']]
sA = (x[0].split() for x in A) # splitting generator
new = [[int(y) for y in x if y is not None] for x in zip_longest(*sA)]
# [[1, 9, 1, 3], [2, 8, 4], [3, 7, 5], [4, 6, 6], [5, 5], [4]]
简单,一行:
from itertools import zip_longest
result = [list(filter(None, i)) for i in zip_longest(*[i[0].split(' ') for i in A])]
您只需检查列表的长度即可。请注意,索引从
0
开始。i、 e.您瞄准的[2,8,4]
是索引[1]
。
使其工作的简单方法:
范围(0,(len(A))内的i的:
一个列表=A[i][0]。拆分(“”)
如果len(一个列表)>1:
new.append(一个列表[1])
但是,请问问你自己,你是否喜欢。想要“错过”缺少的元素,或者你宁愿填补这个空白。例如
范围(0,(len(A))内的i的:
一个列表=A[i][0]。拆分(“”)
如果len(一个列表)>1:
new.append(一个列表[1])
else:new.append(“”)
当你的向量是
['2','8','4']
或['2','8',''4']
时,你面临这个问题,因为你的列表的第三个元素['1']
只是一个元素,在你的循环中,你可以看到new.append(a[i][0]。split('[2])
指的是列表的第三个元素。这就是为什么会出现这个错误
您可以使用try块来解决此问题:
for i in range(0,(len(A))):
try:
new.append(A[i][0].split(' ')[2])
except IndexError:
continue
或者,您可以简单地使用条件块:
for i in range(0,(len(A))):
if len(i) >= 3:
new.append(A[i][0].split(' ')[2])
答复
[[1, 9, 1, 3], [2, 8, 4], [3, 7, 5], [4, 6, 6], [5, 5], [4]]
[Finished in 0.5s]
您可以在追加之前检查长度<代码>拆分=A[i][0];如果len(splitted)>2:您希望结果是int还是strings?为什么
A
包含一个字符串元素列表?
[[1, 9, 1, 3], [2, 8, 4], [3, 7, 5], [4, 6, 6], [5, 5], [4]]
[Finished in 0.5s]