我正在尝试执行列表理解。我想用较大列表的值检查较小列表中的值。我觉得我的代码行得通。直到我的一个内部列表为空。
逻辑是有道理的..。较小列表的位置0处没有元素,因此索引错误:
['w', 'c']
if x[0] != y[0]:
['w', 'c']
IndexError: list index out of range然而,我想知道的是,什么是正确的方式来编写这个s/t它不会在这里出错,而只是假设没有匹配,并转移到list_one中的下一个列表?
下面是我的代码:
a = [['a', 'b', 'c'], ['w', 'c'], []]
b = [['a', 'b', 'c'], ['a', 'f', 'g'], ['x', 'y', 'z']]
def check_contents(list_one, list_two):
if len(list_one)<=len(list_two):
for x in list_one:
for y in list_two:
if x[0] != y[0]:
print(x)
else:
for x in list_two:
for y in list_one:
if x[0] != y[0]:
print(x)
check_contents(a, b)发布于 2018-08-08 00:55:03
首先,你的两个循环做同样的事情。DRY (不要重复自己)。其次,要查看列表是否为空,请检查其真值。空列表求值为False。
def check_contents(list_one, list_two):
shorter, longer = sorted([list_one, list_two], key = len)
for x in longer:
if not x:
continue
for y in shorter:
if not y:
continue
if x[0] != y[0]:
print(x)发布于 2018-08-08 00:48:51
试试这个:
for x, y in zip(list_one, list_two):
if x and y and x[0] != y[0]:
print(x)
else:
# Rest of the code here使用zip()函数创建一个zip对象,这样您就可以同时遍历list-one和list-two,并比较它们的元素。这也解决了你的空列表问题。
发布于 2018-08-08 00:51:42
您可以将条件更改为:
if x and x[0] != y[0]:空列表是假的,而非空列表是真的,因此只有当x为非空(即x[0]存在)时,这才会计算x[0] != y[0]。
https://stackoverflow.com/questions/51731684
复制相似问题