我有一个数据列表:
[[0, 3], [1, 2], [2, 1], [3, 0]]
我正在尝试检查是否有任何单个数字等于 3,如果是,则返回哪个元素,因此原始列表中的 list[0]、list[3] 等包含此值 3。
我已经做到了:
for i in range(0, len(gcounter_selection)):
for x in range(0,len(gcounter_selection)):
if any(x) in gcounter_selection[i][x]==3:
print(i)
顺便说一下,我的列表叫做 gcounter_selection。
但是我遇到了类型错误:
TypeError: argument of type 'int' is not iterable
我试过使用生成器表达式,但我也无法让它工作。
最佳答案
如果我没理解错的话,你正在寻找列表理解:
value = 3
lst = [[0, 3], [1, 2], [2, 1], [3, 0]]
items = [x for x in lst if value in x]
print(items)
#[[0, 3], [3, 0]]
要获取元素的位置而不仅仅是元素,请添加enumerate
:
indexes = [n for n, x in enumerate(lst) if value in x]
关于python - 检查列表中的值是否等于某个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16417324/