如何在python中搜索列表并打印我的条件所在的列表位置?

2024-09-28 05:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在生成一个包含12个随机数的列表:

nums = []    
for num in range(12):
    nums.append(random.randint(1,20))

然后我想在nums中搜索一个特定的数字,比如说12,然后使用if语句打印它是否出现以及在列表中的位置。像这样:

if len(newNums) == 0:
    print('No, 12 is not a part of this integer list')
elif len(newNums) < 2:
    print('Yes, 12 is in the list at index', newNums[0])
else:
    print('Yes, 12 is in the list at indices', newNums)

在本例中,“newNums”是一个列表,其中列出了“12”在“nums”列表中的位置。你知道吗

我用for循环尝试了一些不同的东西,但都没有成功,然后我在这里发现了这样的东西:

newNums = (i for i,x in enumerate(nums) if x == 12)    

然而,当我试图打印,它不做什么,我正在寻找。我一定误解了它的目的。我对enumerate函数的理解是,它提供了值所在位置的索引,然后是值;例如:[0,1][1,8][2,6]等等。我阅读该代码的意思是:如果x == 12,则在列表(nums)中的一对[i,x]中给我I值。你知道吗

在过去的几周里,我对python还很陌生,所以欢迎您提出任何建议。我可能只是误解了代码的工作原理。你知道吗

谢谢你抽出时间。你知道吗


Tags: the代码in列表forlenifis
2条回答

这里唯一的问题是newNums

newNums = (i for i,x in enumerate(nums) if x == 12) # a generator

是一个生成器,据我所知,您不能在一个generator上调用len(..),打印时不会显示它的元素,而只显示它是一个枚举器。你知道吗

您可以使用列表理解来构建列表。您只需将圆括号((..))替换为方括号([..]):

newNums = [i for i,x in enumerate(nums) if x == 12] # a list
#         ^                                       ^

最后一个小提示:

My understanding of the enumerate function is that it provides the index of where the value is located, followed by the value; ex: [0,1], [1,8], [2,6] etc.

你是对的,只是你的语法似乎暗示它发出列表,它发出元组,所以(0,1)(1,8),。。。但这只是一个小细节。你知道吗

代码的一个小问题是

newNums = (i for i,x in enumerate(nums) if x == 12)  

是一个generator(例如len对它不起作用)。你想要的是list (comprehension)

newNums = [i for i,x in enumerate(nums) if x == 12]

有了它,剩下的代码就可以按预期工作了。你知道吗

相关问题 更多 >

    热门问题