我正在搜索3个字符串的元组列表

时间:2013-03-19 10:23:04

标签: python list tuples

我有一个元组列表,例如。

[('ABC', 'Abcair', 1.50), ('DEF', 'Defir', 5.60), ('GHI', 'Ghiair',3.22), ('ANZ', 'Anzplace', 26.25), ('ARG', 'Argair', 12.22), ('CEN', 'Cenair', 11.22), ('CNU', 'Cununun',3.01)]

我有一个输入命令

code_input = input('Please list portfolio: ').upper()

如果某人输入任意数量的由逗号分隔的3个字母代码,我将使用

格式化
no_spaces_codes = code_input.replace(" ", "")
code_list = no_spaces_codes.split(",")

因此,"Ank , ABc,DEF"变为['ANK', 'ABC', 'DEF']

然后我打印这些格式为

的标题
header="{0:<6}{1:<20}{2:>8}".format("Code","Place","Number")
print(header)

然后我需要搜索3个字母代码的元组列表并打印下的值 标题的格式相同,例如,不会打印列表中没有的代码。

Code  Name                   Price
ABC   Abcair                  5.30
DEF   Defair                 11.22

我已经走到了这一步。

for code in b:
    if code[0] == (code_list[1]):
        print(code[:])
        break

打印

Code  Name                   Price
('CEN', 'Contact', 11.22)

但我不能比这更进一步。

2 个答案:

答案 0 :(得分:3)

你可以这样做:

place, price = next((c[1:] for c in b if c[0] == code_input), ('Not found', 0))

但你确实想要使用字典:

code_dict = {k: (v, p) for k, v, p in b}

之后匹配变为简单的查找:

place, price = code_dict.get(code_input, ('Not found', 0))

演示:

>>> b = [('ABC', 'Abcair', 1.50), ('DEF', 'Defir', 5.60), ('GHI', 'Ghiair',3.22), ('ANZ', 'Anzplace', 26.25), ('ARG', 'Argair', 12.22), ('CEN', 'Cenair', 11.22), ('CNU', 'Cununun',3.01)]
>>> code_input = 'CEN'
>>> place, price = next((c[1:] for c in b if c[0] == code_input), ('Not found', 0))
>>> print code_input, place, price
CEN Cenair 11.22
>>> code_dict = {k: (v, p) for k, v, p in b}
>>> place, price = code_dict.get(code_input, ('Not found', 0))
>>> print code_input, place, price
CEN Cenair 11.22

使用code_dict映射,在执行多次查找时,查找将更快,更快,尤其是当列表中存在不存在的条目时。将其与其余代码放在一起:

code_input = input('Please list portfolio: ').upper()
code_dict = {k: (v, p) for k, v, p in b}

line="{0:<6}{1:<20}{2:>8}"
print line.format("Code", "Place", "Number")

for code in code_input.split(','):
    code = code.strip()
    if code not in code_dict:
        continue  # skip codes not in the mapping
    place, price = code_dict[code]
    print line.format(code, place, price)

您的"Ank , ABc,DEF"输入会打印出来:

Code  Place                 Number
ABC   Abcair                   1.5
DEF   Defir                    5.6

答案 1 :(得分:1)

result = [v for v in list_of_tuples if v[0] in code_list]
for v in result:
    print(v) # Or format 'v' tuple in any way you want.