2016-04-26 128 views
-3

我可以用得到的偶数如下:将偶数添加到列表中?

numb=[1,2,3,4,5,6,7,8,9] 
for i in numb: 
    if i%2!=0: 
     continue 
    print(i,end=',') 

我的第一个问题是:我怎么能加入他们吗?即从列表中取出偶数并找出它们的总和? 我的第二个问题是:我可以从用户获取输入,并使用该添加它们:

sums=0 
while True: 
    nums=input('Enter the numbers, leave blank to end :') 
    if nums=='': 
     break 
    else: 
     sums+=int(nums) 
print('Their sum is',sums) 

但如何把来自用户的输入,并把它们放在一起的列表,以便我可以只添加偶数号码?

回答

0

(1)你可以使用这个..创建一个空的列表..并使用append方法将偶数添加到列表中。

numb=[1,2,3,4,5,6,7,8,9] 
    even = [] 
     for i in numb: 
      if i%2!=0: 
       even.append(numb[i]) 
    print(even) 

(2)从用户获取输入并添加全部。另外,您可以使用内置函数sum()。

x = input("how many no. you want to add to the list") 
    list = [] 
    for i in range(x): 
     num = input("Enter the value") 
     list.append(num) 
    print(list) 
    sum1 = sum(list) 
    print("Sum Of all no. in the presented list",sum1) 
+0

所以这就是我错过了。 list_name.append –

-1

使用内置的功能和

print sum(list_) 
0

为了有效地总结了所有甚至任何列表的数量,使用这种生成表达和内置sum功能:

even_sum = sum(x for x in number_list if x%2==0) 

要从用户输入中获得整数的列表,我会推荐以下代码,要求用户在一行中输入逗号分隔的数字:

number_list = [] 
while not number_list: 
    try: 
     number_list = [int(s) for s in input("Enter comma separated numbers: ").split(",")] 
    except ValueError: 
     print("Invalid input. Please only input comma-separated integer numbers.")