问题:如何获取项目在列表中的位置?
我正在遍历列表,如果满足特定条件,我想打印出该项目的索引。我该怎么做?
例:
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
testlist = [1,2,3,5,3,1,2,1,6]
for item in testlist:
if item == 1:
print position
回答 0
嗯 这里有一个关于列表理解的答案,但是它消失了。
这里:
[i for i,x in enumerate(testlist) if x == 1]
例:
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
更新:
好的,您需要一个生成器表达式,我们将有一个生成器表达式。再次在for循环中,这是列表理解:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
现在我们将构建一个生成器…
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
令人高兴的是,我们可以将其分配给变量,然后从那里使用它…
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
并且以为我曾经写过FORTRAN。
Hmmm. There was an answer with a list comprehension here, but it’s disappeared.
Here:
[i for i,x in enumerate(testlist) if x == 1]
Example:
>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]
Update:
Okay, you want a generator expression, we’ll have a generator expression. Here’s the list comprehension again, in a for loop:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
... print i
...
0
5
7
Now we’ll construct a generator…
>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
... print i
...
0
5
7
and niftily enough, we can assign that to a variable, and use it from there…
>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
...
0
5
7
And to think I used to write FORTRAN.
回答 1
接下来呢?
print testlist.index(element)
如果不确定要查找的元素是否确实在列表中,则可以添加初步检查,例如
if element in testlist:
print testlist.index(element)
要么
print(testlist.index(element) if element in testlist else None)
或“ pythonic方式”,我不太喜欢它,因为代码不太清晰,但有时效率更高,
try:
print testlist.index(element)
except ValueError:
pass
What about the following?
print testlist.index(element)
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
if element in testlist:
print testlist.index(element)
or
print(testlist.index(element) if element in testlist else None)
or the “pythonic way”, which I don’t like so much because code is less clear, but sometimes is more efficient,
try:
print testlist.index(element)
except ValueError:
pass
回答 2
使用枚举:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
Use enumerate:
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
回答 3
for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
xrange而不是要求的范围(请参阅注释)。
for i in xrange(len(testlist)):
if testlist[i] == 1:
print i
xrange instead of range as requested (see comments).
回答 4
这是执行此操作的另一种方法:
try:
id = testlist.index('1')
print testlist[id]
except ValueError:
print "Not Found"
Here is another way to do this:
try:
id = testlist.index('1')
print testlist[id]
except ValueError:
print "Not Found"
回答 5
[x for x in range(len(testlist)) if testlist[x]==1]
[x for x in range(len(testlist)) if testlist[x]==1]
回答 6
请尝试以下方法:
testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
Try the below:
testlist = [1,2,3,5,3,1,2,1,6]
position=0
for i in testlist:
if i == 1:
print(position)
position=position+1
回答 7
如果列表足够大,并且只希望在稀疏索引中找到该值,则可以认为该代码可以更快地执行,因为您不必迭代列表中的每个值。
lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
如果您希望找到很多值,则应该将“索引”附加到列表中,并在最后打印列表以节省每次迭代的时间。
If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don’t have to iterate every value in the list.
lookingFor = 1
i = 0
index = 0
try:
while i < len(testlist):
index = testlist.index(lookingFor,i)
i = index + 1
print index
except ValueError: #testlist.index() cannot find lookingFor
pass
If you expect to find the value a lot you should probably just append “index” to a list and print the list at the end to save time per iteration.
回答 8
我认为使用Tkinter库中的curselection()方法可能会很有用:
from Tkinter import *
listbox.curselection()
此方法适用于Tkinter列表框小部件,因此您需要构造其中一个而不是列表。
这将返回如下位置:
(“ 0”,)(尽管Tkinter的更高版本可能会返回一个int列表)
这是第一个位置,编号将根据项目位置而变化。
有关更多信息,请参见以下页面:http : //effbot.org/tkinterbook/listbox.htm
问候。
I think that it might be useful to use the curselection() method from thte Tkinter library:
from Tkinter import *
listbox.curselection()
This method works on Tkinter listbox widgets, so you’ll need to construct one of them instead of a list.
This will return a position like this:
(‘0’,) (although later versions of Tkinter may return a list of ints instead)
Which is for the first position and the number will change according to the item position.
For more information, see this page: http://effbot.org/tkinterbook/listbox.htm
Greetings.
回答 9
为什么使事情复杂化?
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
Why complicate things?
testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
if item == 1:
print position
回答 10
只是为了说明完整的示例,以及input_list
其中具有searies1
(example:input_list [0])的示例,您要在其中查找series2
(example:input_list [1])并获取series2的索引(如果它在series1中存在)。
注意:certain condition
如果条件简单,您将使用lambda表达式
input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)
输出:
[0, 2, 6]
Just to illustrate complete example along with the input_list
which has searies1
(example: input_list[0]) in which you want to do a lookup of series2
(example: input_list[1]) and get indexes of series2 if it exists in series1.
Note: Your certain condition
will go in lambda expression if conditions are simple
input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)
output:
[0, 2, 6]
回答 11
testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
我想这正是您想要的。;-)’id’将始终是列表中值的索引。
testlist = [1,2,3,5,3,1,2,1,6]
for id, value in enumerate(testlist):
if id == 1:
print testlist[id]
I guess that it’s exacly what you want. ;-) ‘id’ will be always the index of the values on the list.
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。