python元组元素的提取_在元组或对象列表上使用Python的list index()方法?

在元组或对象列表上使用Python的list index()方法?

Python的列表类型具有index()方法,该方法带有一个参数,并返回列表中与该参数匹配的第一项的索引。 例如:

>>> some_list = ["apple", "pear", "banana", "grape"]

>>> some_list.index("pear")

1

>>> some_list.index("grape")

3

是否有一种优美的(惯用的)方式将其扩展到诸如元组之类的复杂对象列表? 理想情况下,我希望能够执行以下操作:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

>>> some_list.getIndexOfTuple(1, 7)

1

>>> some_list.getIndexOfTuple(0, "kumquat")

2

get Index Tuple()只是一个假设的方法,该方法接受一个子索引和一个值,然后返回在该子索引处具有给定值的列表项的索引。 我希望

是否有某种方式可以使用列表理解或lambas或类似的“内联”方法来达到一般效果? 我想我可以编写自己的类和方法,但是如果Python已经有办法做到这一点,我就不想重新发明轮子。

12个解决方案

64 votes

这个怎么样?

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

>>> [x for x, y in enumerate(tuple_list) if y[1] == 7]

[1]

>>> [x for x, y in enumerate(tuple_list) if y[0] == 'kumquat']

[2]

正如评论中指出的那样,这将获得所有匹配项。 要获得第一个,您可以执行以下操作:

>>> [y[0] for y in tuple_list].index('kumquat')

2

评论中对所有发布的解决方案之间的速度差异进行了很好的讨论。 我可能有一点偏见,但我个人会坚持一言以蔽之,因为相对于创建函数和导入模块来解决这个问题,我们谈论的速度是微不足道的,但是如果您打算大量这样做 您可能希望查看提供的其他答案,因为它们比我提供的要快。

Paolo Bergantino answered 2020-01-05T22:12:09Z

26 votes

一段时间后,这些列表理解是混乱的。

我喜欢这种Pythonic方法:

from operator import itemgetter

def collect(l, index):

return map(itemgetter(index), l)

# And now you can write this:

collect(tuple_list,0).index("cherry") # = 1

collect(tuple_list,1).index("3") # = 2

如果您需要代码全部都是超级高性能的:

# Stops iterating through the list as soon as it finds the value

def getIndexOfTuple(l, index, value):

for pos,t in enumerate(l):

if t[index] == value:

return pos

# Matches behavior of list.index

raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry") # = 1

Triptych answered 2020-01-05T22:12:37Z

10 votes

一种可能性是使用operator模块中的itemgetter函数:

import operator

f = operator.itemgetter(0)

print map(f, tuple_list).index("cherry") # yields 1

对itemgetter的调用返回一个函数,该函数将对传递给它的任何东西执行foo[0]。 然后,使用map,将该函数应用于每个元组,将信息提取到新列表中,然后像往常一样调用index。

map(f, tuple_list)

等效于:

[f(tuple_list[0]), f(tuple_list[1]), ...etc]

依次等效于:

[tuple_list[0][0], tuple_list[1][0], tuple_list[2][0]]

这使:

["pineapple", "cherry", ...etc]

Jarret Hardie answered 2020-01-05T22:13:15Z

5 votes

您可以使用列表理解和index()

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

[x[0] for x in tuple_list].index("kumquat")

2

[x[1] for x in tuple_list].index(7)

1

Alasdair answered 2020-01-05T22:13:35Z

3 votes

受到这个问题的启发,我发现这很优雅:

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

>>> next(i for i, t in enumerate(tuple_list) if t[1] == 7)

1

>>> next(i for i, t in enumerate(tuple_list) if t[0] == "kumquat")

2

Claudiu answered 2020-01-05T22:13:55Z

2 votes

我会将其作为对Triptych的评论,但是由于缺乏评分,我无法发表评论:

使用枚举器方法匹配元组列表中的子索引。例如

li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),

('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]

# want pos of item having [22,44] in positions 1 and 3:

def getIndexOfTupleWithIndices(li, indices, vals):

# if index is a tuple of subindices to match against:

for pos,k in enumerate(li):

match = True

for i in indices:

if k[i] != vals[i]:

match = False

break;

if (match):

return pos

# Matches behavior of list.index

raise ValueError("list.index(x): x not in list")

idx = [1,3]

vals = [22,44]

print getIndexOfTupleWithIndices(li,idx,vals) # = 1

idx = [0,1]

vals = ['a','b']

print getIndexOfTupleWithIndices(li,idx,vals) # = 3

idx = [2,1]

vals = ['cc','bb']

print getIndexOfTupleWithIndices(li,idx,vals) # = 4

Nisan.H answered 2020-01-05T22:14:19Z

1 votes

好的,这可能是vals(j)中的错误,更正为:

def getIndex(li,indices,vals):

for pos,k in enumerate(lista):

match = True

for i in indices:

if k[i] != vals[indices.index(i)]:

match = False

break

if(match):

return pos

dulce ambrocio answered 2020-01-05T22:14:39Z

1 votes

z = list(zip(*tuple_list))

z[1][z[0].index('persimon')]

eyaler answered 2020-01-05T22:14:55Z

0 votes

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

def eachtuple(tupple, pos1, val):

for e in tupple:

if e == val:

return True

for e in tuple_list:

if eachtuple(e, 1, 7) is True:

print tuple_list.index(e)

for e in tuple_list:

if eachtuple(e, 0, "kumquat") is True:

print tuple_list.index(e)

Ricardo Trujillo answered 2020-01-05T22:15:10Z

0 votes

Python list.index(x)返回列表中第一个x出现的索引。 因此,我们可以传递列表压缩返回的对象以获取其索引。

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]

>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]

[1]

>>> [tuple_list.index(t) for t in tuple_list if t[0] == 'kumquat']

[2]

在同一行中,如果有多个匹配的元素,我们还可以获取索引列表。

>>> tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11), ("banana", 7)]

>>> [tuple_list.index(t) for t in tuple_list if t[1] == 7]

[1, 4]

dspmeng answered 2020-01-05T22:15:35Z

0 votes

我想以下方法不是最好的方法(速度和优雅感),但是可以,它可以帮助您:

from collections import OrderedDict as od

t = [('pineapple', 5), ('cherry', 7), ('kumquat', 3), ('plum', 11)]

list(od(t).keys()).index('kumquat')

2

list(od(t).values()).index(7)

7

# bonus :

od(t)['kumquat']

3

具有2个成员的元组列表可以直接转换为有序dict,数据结构实际上是相同的,因此我们可以即时使用dict方法。

jerome answered 2020-01-05T22:15:59Z

-1 votes

没有身体暗示λ?

Y试试这个,行得通。 我来这篇帖子寻找答案。 我没有发现自己喜欢,但我觉得很疯狂:P

l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]]

map(lambda x:x[0], l).index("pato") #1

编辑添加示例:

l=[['rana', 1, 1], ['pato', 2, 1], ['perro', 1, 1], ['pato', 2, 2], ['pato', 2, 2]]

按条件提取所有项目:         filter(lambda x:x [0] ==“ pato”,l)#[['pato',2,1],['pato',2,2],['pato',2,2]]

根据条件以索引提取所有项目:

>>> filter(lambda x:x[1][0]=="pato", enumerate(l))

[(1, ['pato', 2, 1]), (3, ['pato', 2, 2]), (4, ['pato', 2, 2])]

>>> map(lambda x:x[1],_)

[['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]

注意:_变量仅在交互式解释器中起作用y普通文本文件_需要显式分配,即_ = filter(lambda x:x [1] [0] ==“ pato”,enumerate(l))

Wallebot answered 2020-01-05T22:16:42Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值