如何在 python 中搜索列表并打印我的条件所在的列表位置?
How can I search a list in python and print at which location(s) in that list my criteria is located?
我正在生成一个包含 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]
等。我正在阅读该代码的意思是:给我列表中一对 [i,x]
中的 i 值(nums
) 如果 x == 12
.
我是最近几周 python 的新手,所以欢迎任何建议。我可能只是误解了代码的工作原理。
感谢您的宝贵时间。
这里唯一的问题是 newNums
:
newNums = (i for i,x in enumerate(nums) if x == 12) # a 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 (e.g. len
will not work on it). what you want is a list (comprehension):
newNums = [i for i,x in enumerate(nums) if x == 12]
有了这个,您的其余代码将按预期工作。
我正在生成一个包含 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]
等。我正在阅读该代码的意思是:给我列表中一对 [i,x]
中的 i 值(nums
) 如果 x == 12
.
我是最近几周 python 的新手,所以欢迎任何建议。我可能只是误解了代码的工作原理。
感谢您的宝贵时间。
这里唯一的问题是 newNums
:
newNums = (i for i,x in enumerate(nums) if x == 12) # a 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 (e.g. len
will not work on it). what you want is a list (comprehension):
newNums = [i for i,x in enumerate(nums) if x == 12]
有了这个,您的其余代码将按预期工作。