Python 从其他列表变量生成新列表
当我想从精心选择的整数变量中创建一个新列表,并询问新列表的总和时,我得到的答案总是0Python 从其他列表变量生成新列表,python,list,math,append,Python,List,Math,Append,当我想从精心选择的整数变量中创建一个新列表,并询问新列表的总和时,我得到的答案总是0 else: if "--" in epart: epart = epart[2:] esplit = [int(epart) for epart in esplit] total.append(epart) else: epart = [int(epart) for epart
else:
if "--" in epart:
epart = epart[2:]
esplit = [int(epart) for epart in esplit]
total.append(epart)
else:
epart = [int(epart) for epart in esplit]
total.append(epart)
print sum(total)
代码顶部是:
total = []
如果出现以下情况,如何获取代码以打印总计的总和:
esplit = ["34", "-3", "5", "--4"]
for epart in esplit:
程序应该打印40,而不是0。您可以使用“string.replace”将“-”转换为“”,然后将值转换为int
:
esplit = ["34", "-3", "5", "--4"]
print sum([int(elem[2:]) if "--" in elem else int(elem) for elem in esplit])
>>> esplit = ["34", "-3", "5", "--4"]
>>> sum([int(itm.replace("--", "")) for itm in esplit])
40
您可以使用“string.replace”将“-”转换为“”,然后将值转换为int
:
>>> esplit = ["34", "-3", "5", "--4"]
>>> sum([int(itm.replace("--", "")) for itm in esplit])
40
您可以使用“string.replace”将“-”转换为“”,然后将值转换为int
:
>>> esplit = ["34", "-3", "5", "--4"]
>>> sum([int(itm.replace("--", "")) for itm in esplit])
40
您可以使用“string.replace”将“-”转换为“”,然后将值转换为int
:
>>> esplit = ["34", "-3", "5", "--4"]
>>> sum([int(itm.replace("--", "")) for itm in esplit])
40