简体   繁体   English

如何从python(3.3)中的列表中获取元组

[英]How can I get a Tuple from a list in python (3.3)

So I've been given a module with a list of tuples in it. 因此,我得到了一个包含元组列表的模块。 Each tuple has 3 items, a company code, the company name, and the company price: 每个元组有3个项目,公司代码,公司名称和公司价格:

('bwt', 'bigwilsontrans', 23.4)

This list has quite a few items in it. 此列表中有很多项。 What I've been asked to do is write a program that asks the user for input of the company's code (can be more than one) and returns the tuple from the list with that corresponding code in it. 我被要求做的是编写一个程序,要求用户输入公司代码(可以是多个),然后从列表中返回包含相应代码的元组。

If the code doesn't match any in the list, that code is ignored. 如果代码与列表中的任何代码都不匹配,则将忽略该代码。 Can anyone help? 有人可以帮忙吗? I'm stuck on how to return the tuple. 我被困在如何返回元组上。 I am quite new to python so sorry if this seems basic 我对python很陌生,所以如果这很基本,请抱歉

You can access the individual members of a tuple using indexes as if it was an array, see the relevant python docs for more info. 您可以像使用数组一样使用索引访问元组的各个成员,有关更多信息,请参见相关的python文档

So this is a pretty simple matter of grabbing your needle (the company code) from the haystack (a list of tuples) 因此,从干草堆(元组列表)中抢针(公司代码)是一件非常简单的事情

# haystack is a list of tuples
def find_needle(needle, haystack):
  for foo in haystack:
    # foo is a tuple, notice we can index into it like an array
    if foo[0] == needle:
      print foo

Let list_ be the list of tuples and c_code the company code, read from input via raw_input or from some GUI via some control (if you need help with that, please tell me. list_为元组列表,并c_code公司代码,通过raw_input从输入中读取,或通过某些控件从某些GUI中读取(如果需要帮助,请告诉我。

You could use either list comprehension: 您可以使用任一列表理解:

matching_results = [t for t in list_ if t[0] == c_code]

or the built-in filter function: 或内置的filter功能:

matching_results = filter(lambda t: t[0]==c_code, list_)

Be careful with version 2: in Python 3, filter is generator-style, ie it does not create a list, but you can iterate over it. 请注意版本2:在Python 3中, filter是生成器样式的,即,它不会创建列表,但可以对其进行迭代。 To get a list in Python 3, you would have to call list(...) on this generator. 要在Python 3中获取列表,您必须在此生成器上调用list(...)

EDIT 编辑

If you have a list of company codes, c_codes , you can do 如果您有公司代码c_codes的列表, c_codes可以执行

matching_results = [t for t in list_ if t[0] in c_codes]

This should be the easiest possible way. 这应该是最简单的方法。

It sounds like you almost definitely want to use a dict . 听起来您几乎绝对想使用dict

companies = { "bwt": (bigwilsontrans, 23.4),
              "abc": (alphabet, 25.9)
            }

Then to look it up, you can simply do: 然后要查找它,您只需执行以下操作:

code = int(raw_input("Code: "))
print companies[code]

try: 尝试:

>>>tuple([1, 2, 3])
(1, 2, 3)

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

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