我的老師給了我一個問題,它應該給出他在在線 python 編譯器中期望的準確輸出:
撰寫一個 Python 程式,獲取某百貨公司顧客購買的商品集合,并根據輸入的商品名稱按升序列印所有購買過特定商品的顧客姓名。
我將其解決為:
l1 = [] #list for the products
l2 = [] #list for the people who were found to be using the product which was searched
l3 = [] #list for the names of people who bought the product
l5 = [] #list of all the products in the order they were bought
z = 0 #length of list l5
a = input('')#Number of people who wish to buy
b = input('')#Number of products which are to be bought
if a.isdigit() and b.isdigit():
a = int(a)
b = int(b)
d1 = {} #Dictionary which stores the names and corresponding products.
for i in range(1, a 1):
name1 = input('')
name = name1.replace("'", "")
l3.append(name)
l1 = [] #list for the products
for j in range(1, b 1):
prod1 = input('')
prod = prod1.replace("'", "")
l1.append(prod)
d1[name] = l1
for x in range(0, a):
l5 = l5 d1[l3[x]]
com1 = input('') #product name which is to be searched
com = com1.replace("'", "")
if com in l5:
z = len(l5)
for ind in range(z):
if com == l5[ind]:
for z2 in range(a):
z3 = ind - (z2*a)
if 0 < z3 < b:
l2.append(l3[z3])
else:
pass
for m in range(len(l2)):
print(l2[m])
else:
print("Invalid product")
else:
print("Invalid input")
但是輸出只給了我最終的名字,這是共同的:
4 #Number of people
5 #Number of products
armaan
a
s
d
f
g
harry
d
c
f
v
g
michael
w
a
s
x
c
john
r
d
v
g
a
a #Product to be searched
john #Output
Process finished with exit code 0
雖然預期結果是:
4 #Number of people
5 #Number of products
armaan
a
s
d
f
g
harry
d
c
f
v
g
michael
w
a
s
x
c
john
r
d
v
g
a
a #Product to be searched
armaan
michael
john #Output
Process finished with exit code 0
請幫我解決這個問題
uj5u.com熱心網友回復:
你可以這樣解決——
people=int(input('')) #get number of people
prod_count=int(input('')) #get number of products
prods=[] #list containing the names of people and their corresponding products - [['armaan',['a','s','d','f','g']],...]
for i in range(people):
name=input('') #name of the person
products=[input('') for j in range(prod_count)] #this is a single line for looping the amount of times specified at the start in prod_count and storing the values in a list - ['a','s','d','f','g']
prods.append([name,products]) #appending the name and the product list of the name to the main list
#print the final names
for i in prods: #iterating over the main list
products=i[1] #getting the products - ['a','s','d','f','g']
if input('') in products: #if the user inputted product name is in the list of products
print(i[0]) #then print the name of the user
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398307.html
上一篇:隨著時間的推移創建累積串列
下一篇:將字典串列分成多個串列
