python列表找位置_如何在Python列表中找到項目的位置?

I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:

我想在列表列表中找到特定項目的位置。它應該返回一個元組列表,其中每個元組代表該項的特定實例的索引。例如:

list = [['1', '2', '4', '6'], ['7', '0', '1', '4']]

getPosition('1') #returns [(0, 0), (1, 2)]

and getPosition('7') #returns [(1,0)]

9 个解决方案

#1

7

If you want something that will both

如果你想要兩種東西

find duplicates and

找到重復和

handle nested lists (lists of lists of lists of ...)

處理嵌套列表(列表列表...)

you can do something like the following:

你可以做類似以下的事情:

def get_positions(xs, item):

if isinstance(xs, list):

for i, it in enumerate(xs):

for pos in get_positions(it, item):

yield (i,) + pos

elif xs == item:

yield ()

Testing this:

>>> xs = [['1', '2', '4', '6'],

... ['7', '0', '1', '4'],

... [ [ '0', '1', '1'], ['1']]

... ]

>>> print list(get_positions(xs, '1'))

[(0, 0), (1, 2), (2, 0, 1), (2, 0, 2), (2, 1, 0)]

#2

5

It looks likes you want, for a list of sublists and a given item, to return a list of pairs where each pair is (the index of the sublist, the index of the item within the sublist). You can do that using list comprehensions and Python's built in enumerate() function:

對於子列表和給定項目的列表,您看起來想要返回每對對的列表列表(子列表的索引,子列表中項目的索引)。您可以使用列表推導和Python內置的enumerate()函數來實現:

def getPosition(list, item):

return [(i, sublist.index(item)) for i, sublist in enumerate(list)]

Edit: See @scribble's answer above/below.

編輯:請參閱上面/下面的@ scribble的回答。

#3

3

def getPosition(list, item):

return [(i, sublist.index(item)) for i, sublist in enumerate(list)

if item in sublist]

#4

2

def get_positions(xs, target):

return [(i,e.index(target)) for i,e in enumerate(xs)]

That's a good starting point. Presumably you have some sort of class such as

這是一個很好的起點。大概你有某種類如

class SomeClass:

def __init__(self):

self.xs = [['1','2','4','6'], ['7','0','1','4']]

def get_positions(self, target):

return [(i,e.index(target)) for i,e in enumerate(self.xs)]

which in this case would let you say

在這種情況下會讓你說

model = SomeClass()

model.get_position(1) # returns [(0,0), (1,2)]

Note that in both cases you'll get an exception if your target isn't in every one of your sublists. The question does not specify whether this is the desired behavior.

請注意,在這兩種情況下,如果您的目標不在每個子列表中,您將收到異常。問題沒有說明這是否是所需的行為。

#5

2

If you don't want a exception if the item is not in the list try this. Also as a generator because they are cool and versatile.

如果您不希望例外,如果該項目不在列表中,請嘗試此操作。也作為發電機,因為它們很酷且功能多樣。

xs = [['1', '2', '4', '6'], ['7', '0', '1', '4']]

def get_positions(xs, item):

for i, xt in enumerate( xs ):

try: # trying beats checking

yield (i, xt.index(item))

except ValueError:

pass

print list(get_positions(xs, '1'))

print list(get_positions(xs, '6'))

# Edit for fun: The one-line version, without try:

get_positions2 = lambda xs,item: ((i,xt.index(item)) for i, xt in enumerate(xs) if item in xt)

print list(get_positions2(xs, '1'))

print list(get_positions2(xs, '6'))

#6

0

A while ago I wrote a library for python to do list matching that would fit the bill pretty well. It used the tokens ?, +, and * as wildcards, where ? signifies a single atom, + is a non-greedy one-or-more, and * is greedy one-or-more. For example:

前段時間我為python寫了一個庫來做列表匹配,很適合這個法案。它使用令牌?,+和*作為通配符,在哪里?表示單個原子,+是非貪婪的一個或多個,*是貪婪的一個或多個。例如:

from matching import match

match(['?', 2, 3, '*'], [1, 2, 3, 4, 5])

=> [1, [4, 5]]

match([1, 2, 3], [1, 2, 4])

=> MatchError: broken at 4

match([1, [2, 3, '*']], [1, [2, 3, 4]])

=> [[4]]

match([1, [2, 3, '*']], [1, [2, 3, 4]], True)

=> [1, 2, 3, [4]]

在這里下載:http://www.artfulcode.net/wp-content/uploads/2008/12/matching.zip

#7

0

Here is a version without try..except, returning an iterator and that for

這是一個沒有try..except的版本,返回一個迭代器和for

[['1', '1', '1', '1'], ['7', '0', '4']]

returns

[(0, 0), (0, 1), (0, 2), (0, 3)]

def getPosition1(l, val):

for row_nb, r in enumerate(l):

for col_nb in (x for x in xrange(len(r)) if r[x] == val):

yield row_nb, col_nb

#8

0

The most strainghtforward and probably the slowest way to do it would be:

最緊張,也可能是最慢的方法是:

>>> value = '1'

>>> l = [['1', '2', '3', '4'], ['3', '4', '5', '1']]

>>> m = []

>>> for i in range(len(l)):

... for j in range(len(l[i])):

... if l[i][j] == value:

... m.append((i,j))

...

>>> m

[(0, 0), (1, 3)]

#9

0

Here is another straight forward method that doesn't use generators.

這是另一種不使用生成器的直接方法。

def getPosition(lists,item):

positions = []

for i,li in enumerate(lists):

j = -1

try:

while True:

j = li.index(item,j+1)

positions.append((i,j))

except ValueError:

pass

return positions

l = [['1', '2', '4', '6'], ['7', '0', '1', '4']]

getPosition(l,'1') #returns [(0, 0), (1, 2)]

getPosition(l,'9') # returns []

l = [['1', '1', '1', '1'], ['7', '0', '1', '4']]

getPosition(l,'1') #returns [(0, 0), (0, 1), (0,2), (0,3), (1,2)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值