【发布时间】:2020-07-28 20:09:17
【问题描述】:
说我有一个
list=['apple','orange','durian','blackberry']
如何使用 while 或 for 循环找到 'durian' 的位置
我知道有一个代码叫list.index('durian')
但我想知道使用 for/while 循环的特定项目的位置
【问题讨论】:
标签: python for-loop while-loop
说我有一个
list=['apple','orange','durian','blackberry']
如何使用 while 或 for 循环找到 'durian' 的位置
我知道有一个代码叫list.index('durian')
但我想知道使用 for/while 循环的特定项目的位置
【问题讨论】:
标签: python for-loop while-loop
你可以使用enumerate(...):
lst = ['apple', 'orange', 'durian', 'blackberry']
for idx, value in enumerate(lst):
if value == "durian":
print(idx)
【讨论】:
您可以使用 for 循环使用 range(len(list)) 遍历列表的长度,如下所示。 len(list) 返回列表中的索引数,因此在这种情况下为 3,使用 range() 函数将有助于多次迭代/循环列表。 请记住,在列表中,第一个值位于第 0 个索引处,第二个值位于第 1 个索引处,依此类推。
list_sample = ['apple', 'orange', 'durian', 'blackberry']
for i in range(len(list_sample)):
if list_sample[i] == 'durian':
print("Index Position of 'durian' in the list is " + str(i))
else:
pass
或者您可以使用如下 enumerate() 函数:
list_sample = ['apple', 'orange', 'durian', 'blackberry'] # apple is at the
for i, value in enumerate(list_sample):
if value == 'durian':
print("Index Position of 'durian' in the list is " + str(i))
else:
pass
【讨论】:
一种方式:
while list.pop() != 'durian':
pass
print(len(list))
另一个:
i = 0
while list[i] != 'durian':
i = random.randrange(len(list))
print(i)
恕我直言,比无聊的范围/枚举更有趣:-)
【讨论】:
list.index('durian') 一样。就像我提到的,这些都是为了好玩。我认为很明显我并不是在认真建议在严肃的事情上使用这些。
为什么要这样做?
如果你真的想要,代码功能很简单
def getindex(l: list, element) -> int:
for i, e in enumerate(l):
if e == element:
return i
raise ValueError(f"{element} is not in list")
【讨论】:
在 python 中,list[int] 用于查找元素在列表中的位置,其中int 是您想要的项目的索引。
在您的情况下,这将是 list[2]。请注意,我们从索引 0 开始计数。
【讨论】: