我在程序中有2个列表。一个列表是5个泛型整数的列表,第二个列表包含5个用户输入的整数。 现在,我需要比较每个用户号码是否在通用号码列表上。 如果是这样,请向播放器添加一个点。 我不知道从哪里开始。 我真的不想要一个完整的答案,但是我找不到任何教程进行这种比较,因此,我将不胜感激。
import random
#Winning numbers
def winningNumbers():
winning_numbers = []
for i in range(5):
x = random.randint(1,50)
winning_numbers.append(x)
print("Today's winning numbers are: " + str(winning_numbers))
return winning_numbers
#Get player numbers
def player_numbers():
user_input = []
while len(user_input) < 5:
number = input("Chose the numbers from 1-50:")
try:
number = int(number)
except ValueError:
print("That's not a number!")
continue
if number in user_input:
print("You already chosen this number!")
elif number not in range(1,51):
print("The number is out of range")
else:
user_input.append(number)
print("Your chosen numbers are: " + str(user_input))
return user_input
#Compare numbers
def compare_numbers():
player_points = 0
for i in winning_numbers:
for x in user_input:
if str(x) == str(y):
player_points = player_points + 1
else:
pass
print(player_points)
winningNumbers()
player_numbers()
compare_numbers()
答案 0 :(得分:2)
我能够从GeeksForGeeks Comparing Python Lists那里获得
该程序将打印出两个列表中都存在的元素。
# Python program to find the common elements
# in two lists
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements")
a = [1, 2, 3, 4, 5] # here is where you would gather the lists
b = [5, 6, 7, 8, 9]
common_member(a, b)
答案 1 :(得分:0)
您可以做的最好的事情就是创建一个嵌套循环,这样就可以在一个循环中循环。这样做:
for i in list1:
for x in list2:
if str(x) == str(i):
#Do stuff, like add up point
else:
#Do stuff, like subtract points, or put in 'pass' for Python to pass the condition
我希望这对您有所帮助。如果您还有更多的海藻,我会为他们开放。
编辑:此代码有效,请尝试了解:
import random
global player_points
player_points = 0
#Winning numbers
def winningNumbers():
winning_numbers = []
for i in range(5):
x = random.randint(1,50)
winning_numbers.append(x)
print("Today's winning numbers are: " + str(winning_numbers))
return winning_numbers
#Get player numbers
def player_numbers(winning_numbers):
user_input = []
while len(user_input) < 5:
number = input("Chose the numbers from 1-50:")
try:
number = int(number)
except ValueError:
print("That's not a number!")
continue
if number in user_input:
print("You already chosen this number!")
elif number not in range(1,51):
print("The number is out of range")
else:
user_input.append(number)
print("Your chosen numbers are: " + str(user_input))
return user_input
#Compare numbers
def compare_numbers(user_input, winning_numbers):
global player_points
for i in winning_numbers:
for x in user_input:
if str(x) == str(i):
player_points = player_points + 1
else:
pass
print(player_points)
#Loop functions
while True:
compare_numbers(player_numbers(winningNumbers()), winningNumbers())
问候,来自CCD的Chris van den Hoorn
答案 2 :(得分:0)
使用
set(user_input_list) & set(generic_list)
以获得两个列表中的通用值。