简体   繁体   中英

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:

('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

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.

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.

You could use either list comprehension:

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

or the built-in filter function:

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. To get a list in Python 3, you would have to call list(...) on this generator.

EDIT

If you have a list of company codes, c_codes , you can do

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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