如何在给定某些约束的情况下打印出列表的总和

时间:2015-08-28 14:38:08

标签: python list dictionary sum

我试图打印通过raw_input生成的列表的总和。

列表中的数字必须介于1和1000之间。列表的长度必须低于1000.

到目前为止,这是我的代码:

initial_list = raw_input()

integer= initial_list.split(' ') 
if len(integer) <= 1000:
    for i in integer: 
        if i >= 1 and i<=1000:
            actual_integer = map( int, integer)
            print sum(actual_integer)

这不会打印任何内容。有什么建议和/或替代方案吗?

3 个答案:

答案 0 :(得分:2)

如果我理解你的目标,你已经得到了所有正确的想法,你只需要稍微重新整理你的逻辑,并确保你清楚自己何时处理你的问题。一个值列表以及当您处理单个值时。

您可能也希望考虑变量命名,因为好的名称可以帮助您跟踪变量是否具有多个值或单个值的类型。我已将此代码更新为

IPagedCollection<IDirectoryObject> pagedCollection = retrievedUserFetcher.MemberOf.ExecuteAsync();

答案 1 :(得分:0)

这里的代码可以满足您的需求,但没有错误检查。

initial_list = raw_input()  # there should be some prompt text

# no error checking
integer = initial_list.split(' ')
# no output for lists > 1000
if len(integer) <= 1000:
    print sum(filter(lambda i: 0 < i <= 1000, map(int, integer)))

输出

$ python test.py
1 2 3 1500 0
6

答案 2 :(得分:0)

如果我理解你的问题,这可能是你正在寻找的。

此代码将提示输入并将输入附加到列表lst,直到lst将包含1000个元素。如果输入是1到1000之间的数字,它只会输入一个输入,并且在每次输入后都会给你sum

lst = []
while len(lst) <= 999:
    initial_list = raw_input('Input numbers between 1 and 1000:')
    if initial_list.isdigit() and int(initial_list) <= 1000 and int(initial_list) >= 1:
        lst.append(int(initial_list))
        print 'List:', lst #prints the list
        total = sum(lst)  
        print 'List Sum:', total #prints the list sum
    else:
        print 'Input must be numbers between 1 and 1000'

输出:

Input numbers between 1 and 1000:12
List: [12]
List Sum: 12
Input numbers between 1 and 1000:45
List: [12, 45]
List Sum: 57
Input numbers between 1 and 1000:156
List: [12, 45, 156]
List Sum: 213
Input numbers between 1 and 1000:256
List: [12, 45, 156, 256]
List Sum: 469
Input numbers between 1 and 1000: