gpt4 book ai didi

python - 如何从列表列表中获取整数

转载 作者:行者123 更新时间:2023-12-01 06:28:19 24 4
gpt4 key购买 nike

我有这个列表:

lst =[[5,5,5,5],[5,0,1,5],[5,0,3,5],[5,2,3,5],[5,5,5,5]]

我需要某种函数来搜索一个特定的数字(例如 1),其输出如下所示:

 >>> It's in a list with index 1
>>> In list with index 1, it has index 2

或者甚至更简单的东西,例如:

>>> 1
>>> 2

提前非常感谢您!

最佳答案

这是一个更简洁的版本,对我来说似乎更实用:

def find_int(l, target):
sub_list = [x for x in range(len(l)) if target in l[x]][0]
return sub_list, l[sub_list].index(target)


>>> lst = [[5,5,5,5],[5,0,1,5],[5,0,3,5],[5,2,3,5],[5,5,5,5]]
>>> print(find_int(lst,2))
(3, 1)

这是一个带有可爱文本的版本,它返回的结果与您指定的完全相同:

def find_int(l, target):
for sub_list in range(len(l)):
if target in l[sub_list]:
print("It's in a list with index " + str(sub_list))
print("In list with index " + str(sub_list) + ", it has index " + str(l[sub_list].index(target)))
return

>>> lst = [[5,5,5,5],[5,0,1,5],[5,0,3,5],[5,2,3,5],[5,5,5,5]]
>>> find_int(lst,2)
It's in a list with index 3
In list with index 1, it has index 1

关于python - 如何从列表列表中获取整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com