![](/img/trans.png)
[英]How do I call values from two different lists, in pairs, to specify parameters of two sequential stimuli in Python?
[英]Python Generator: How do I generate pairs from two different lists based on user input (of how many pairs to print)
鑒於有兩個列表:
colorList1 = ['red', 'orange', 'pink', 'brown', 'green', 'yellow']
colorList2 = ['purple', 'blue', 'violet', 'black, 'cyan', 'white']
如何根據用戶輸入的數字從列表開頭開始從每個列表(每行)生成和打印 1 種顏色。 並且,如何在用戶按下 Enter 鍵之前每次只生成最多 2 對顏色。
例子:
userinput = int(input("Enter a limit: ")) # user enters 5
輸出:
red purple
orange blue
press Enter key for next 2 pairs of colors # user presses Enter key to generate the next pair
pink violet
brown black
press Enter key for next 2 pairs of colors # user presses Enter key to generate the next pair
green cyan # last pair since user entered 5
End of list of colors
你可以嘗試這樣的事情。
colorList1 = ['red', 'orange', 'pink', 'brown', 'green', 'yellow']
colorList2 = ['purple', 'blue', 'violet', 'black', 'cyan', 'white']
def print_color():
userInput = input("Enter amount to print: ")
try:
userInput = int(userInput)
except ValueError:
print("User Input must be a positive integer")
return
if userInput < 0:
print("User Input must be a positive integer")
return
for i in range(0, int(userInput)):
if i >= len(colorList1) or i >= len(colorList2):
print("End of list of colors")
return
if i % 2 == 0 and i != 0:
input("press Enter key for next 2 pairs of colors")
print(colorList1[i], colorList2[i])
print_color()
編輯:我已更新代碼以包含基本錯誤檢查
你可以這樣做:
colorList1 = ['red', 'orange', 'pink', 'brown', 'green', 'yellow']
colorList2 = ['purple', 'blue', 'violet', 'black', 'cyan', 'white']
color_pairs = iter(zip(colorList1,colorList2))
userinput = int(input("Enter a limit: ")) # user enters 5
i = 0
while i<userinput:
if i%2 == 0: input(f"press Enter key for next 2 pairs of colors")
print(*next(color_pairs))
if i+1 == len(colorList1):
break
i += 1
print("\nEnd of list of colors")
輸出:
Enter a limit: 5
press Enter key for next 2 pairs of colors
red purple
orange blue
press Enter key for next 2 pairs of colors
pink violet
brown black
press Enter key for next 2 pairs of colors
green cyan
End of list of colors
Enter a limit: 7
press Enter key for next 2 pairs of colors
red purple
orange blue
press Enter key for next 2 pairs of colors
pink violet
brown black
press Enter key for next 2 pairs of colors
green cyan
yellow white
End of list of colors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.