简体   繁体   English

具有数字和字符串的元组列表

[英]List of tuples with numbers and strings

I have a list of tuples, which may look like this: 我有一个元组列表,看起来像这样:

[(23, 'somestr'), (30, 'someotherstr'), (15, 'someotherstr2')]

I need to extract the tuple which has the minimum number, and get the string of that tuple. 我需要提取具有最小数目的元组,并获取该元组的字符串。 To find the minimum, I just did: min([i[0] for i in list]) . 为了找到最小值,我只是做了: min([i[0] for i in list])

How would get the string though? 怎么会得到字符串呢? A nested list comprehension? 嵌套列表理解? I've tried several ways but I',m not sure how to either retain the tuple's index, or get it within the list comprehension statement. 我已经尝试了几种方法,但是我不确定如何保留元组的索引,或者如何在列表理解语句中获取它。

min(your_list)[1] #would be sufficient

Here, you can just compare the tuples directly. 在这里,您可以直接比较元组。 However, a more general approach is to use the key argument to min() : 但是,更通用的方法是使用min()key参数:

In [21]: min(l, key=operator.itemgetter(0))[1]
Out[21]: 'someotherstr2'

Here, key=operator.itemgetter(0) extracts the zeroth element of the tuple and uses the result as the key to decide which tuple is the smallest. 在这里, key=operator.itemgetter(0)提取元组的第零个元素,并使用结果作为关键字来确定哪个元组最小。

Tuples can be compared: 元组可以比较:

>>> (1, 'hello') < (2, 'bye')
True

Tuples are compared kind of like strings: consider elements pairwise until you find an unequal pair, and then the tuple with the smaller element is considered smaller. 比较元组就像是字符串:将元素成对考虑,直到找到不相等的对,然后将具有较小元素的元组视为较小。

So you can simply get the minimum of the list, and the tuple with the lowest first value will be returned. 因此,您只需获取列表的最小值,就会返回具有最低第一个值的元组。 Then you can look at the string in the second element: 然后,您可以查看第二个元素中的字符串:

least = min(the_list)
print least[1]
    python 3.2

    1. min(your_list)

    2. sorted(your_list)[0]

    3. min([(i,v) for i,v in your_list])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM