2013-03-28 78 views
0

在python 3中,我有一行要求輸入,然後輸入,然後查看導入的字典,然後列出出現在字典中的所有輸入。我的問題是當我運行代碼並放入輸入時,它只會返回我輸入的最後一個單詞。 例如 該字典包含(AIR,AMA) ,如果我輸入(AIR,AMA),它將只返回AMA。 任何信息解決這將是非常有益的!返回多個輸入(Python)

字典:

EXCHANGE_DATA = [('AIA', 'Auckair', 1.50), 
       ('AIR', 'Airnz', 5.60), 
       ('AMP', 'Amp',3.22), 

驗證碼:

import shares 
a=input("Please input") 
s1 = a.replace(' ' , "") 
print ('Please list portfolio: ' + a) 
print (" ") 
n=["Code", "Name", "Price"] 
print ('{0: <6}'.format(n[0]) + '{0:<20}'.format(n[1]) + '{0:>8}'.format(n[2])) 
z = shares.EXCHANGE_DATA[0:][0] 
b=s1.upper() 
c=b.split() 
f=shares.EXCHANGE_DATA 
def find(f, a): 
    return [s for s in f if a.upper() in s] 
x= (find(f, str(a))) 
toDisplay = [] 
a = a.split() 
for i in a: 
    temp = find(f, i) 
    if(temp): 
     toDisplay.append(temp) 
for i in toDisplay: 
    print ('{0: <6}'.format(i[0][0]) + '{0:<20}'.format(i[0][1]) + ("{0:>8.2f}".format(i[0][2]))) 
+0

代碼示例會有幫助,因爲我不知道你在說什麼。 – brice 2013-03-28 10:48:20

+0

更新了代碼 – user2101517 2013-03-28 10:54:28

+0

Thankyou,這有助於很多:) – brice 2013-03-28 10:57:43

回答

1

好了,代碼似乎有些困惑。這裏有一個,似乎你想要做什麼簡單的版本:

#!/usr/bin/env python3 

EXCHANGE_DATA = [('AIA', 'Auckair', 1.50), 
       ('AIR', 'Airnz', 5.60), 
       ('AMP', 'Amp',3.22)] 

user_input = input("Please Specify Shares: ") 

names = set(user_input.upper().split()) 

print ('Listing the following shares: ' + str(names)) 
print (" ") 

# Print header 
n=["Code", "Name", "Price"] 
print ('{0: <6}{1:<20}{2:>8}'.format(n[0],n[1],n[2])) 

#print data 
for i in [data for data in EXCHANGE_DATA if data[0] in names]: 
    print ('{0: <6}{1:<20}{2:>8}'.format(i[0],i[1],i[2])) 

下面是使用的例子:

➤ python3 program.py 
Please Specify Shares: air amp 
Listing the following shares: {'AMP', 'AIR'} 

Code Name     Price 
AIR Airnz     5.6 
AMP Amp      3.22 

你實際提供的代碼示例不會是預期,如果你給它的空間分隔報價名稱。

希望這會有所幫助。

+0

非常感謝你的幫助!這當然會使它更清楚,如果輸入包含逗號,它是否可以以相同的方式工作? (例如air,amp,aia)再次感謝 – user2101517 2013-03-28 11:31:45

+0

,您可以通過使用're'模塊來分割輸入。例如,用'names = set(re.split(「[\ t。,] *」,user_input))替換'names = set(user_input.upper()。split())''看看[ (http://docs.python.org/3/library/re.html#re.split)瞭解更多信息。 – brice 2013-03-28 11:36:58

+0

還要注意,上面的解決方案在計算上很昂貴(通過每個股票價格清單),並且可能有更好的方法來做到這一點。 – brice 2013-03-28 11:42:39