我正在尝试创建一个新列表,对两个python列表执行逐元素构造,如下所示:
from operator import add
number_villains_players = 0
villain_strength = []
player_strength = []
resulten_strength = []
def get_villain_strength(size):
villain_strength = [int(x) for x in input("Enter {} numbers of space separated strength of Villains:".format(size)).split()]
print(villain_strength)
def get_player_strength(size):
player_strength = [int(x) for x in input("Enter {} numbers of space separated energy of Players:".format(size)).split()]
print(player_strength)
def compare_strength():
#resulten_strength = [m-n for (m,n) in zip(player_strength,villain_strength)] #doesn't work
#resulten_strength = [sum(x) for x in zip(player_strength, villain_strength)] #doesn't work
#resulten_strength = [list( map(add, player_strength, villain_strength) )] #doesn't work
resulten_strength = [a*b for a,b in zip(player_strength,villain_strength)] #doesn't work
print(resulten_strength)
def main():
number_villains_players = input("How many Players/Villains?:")
get_villain_strength(number_villains_players)
get_player_strength(number_villains_players)
compare_strength()
if (i > 0 for i in resulten_strength):
print("WIN")
else:
print("LOSE")
main()
但是print(resulten_strength)
始终为[]
或[[]]
我遵循了以下所有可能的解决方案:
有人可以指出我要去哪里吗?
答案 0 :(得分:4)
您正在方法中分配本地列表,它们不是全局的。因此,定义的顶行始终为空。这应该可以解决您的问题:
#!/usr/bin/env python3
import cgi,cgitb
import urllib.request
from bs4 import BeautifulSoup
from bs4.element import Comment
from datetime import datetime
import re
import json
print ("Content-Type: text/plain;charset=utf-8\n")
print("hello")
但是在任何地方使用全局变量都是不好的。您可能想要一个带有返回值的函数。
在函数内分配相同的名称变量时,它将覆盖全局变量的名称,直到从函数返回为止。或者说,如果您查找变量,它将首先在def get_villain_strength(size):
global villain_strength
villain_strength = [int(x) for x in input("Enter {} numbers of space separated strength of Villains:".format(size)).split()]
print(villain_strength)
中查找名称,如果找不到任何内容,它将转到locals()
。如果仍然找不到任何内容,则会引发异常。
答案 1 :(得分:2)
我不确定这是您要找的东西。我对您的代码做了一些小的修改。我删除了变量声明并修改了函数。
def get_villain_strength(size):
villain_strength = [int(x) for x in input("Enter {} numbers of space separated strength of Villains:".format(size)).split()]
print (villain_strength)
return(villain_strength)
def get_player_strength(size):
player_strength = [int(x) for x in input("Enter {} numbers of space separated energy of Players:".format(size)).split()]
print (player_strength)
return(player_strength)
def compare_strength(x,y):
resulten_strength = [a*b for a,b in zip(x,y)]
return(resulten_strength)
def main():
number_villains_players = input("How many Players/Villains?:")
x = get_villain_strength(number_villains_players)
y = get_player_strength(number_villains_players)
print (compare_strength(x,y))