簡體   English   中英

總結一個列表的對象

[英]sum up objects of a list

我正在編寫一個應該采用文件名並創建初始列表的代碼。 然后,我試圖總結列表中的每個項目。 我到目前為止編寫的代碼看起來像這樣......

filename = input('Enter filename: ')
    Lists = []
    for line in open(filename):
        line = line.strip().split()
        Lists = line
    print(Lists)
    total = 0
    for i in Lists:
        total = sum(int(Lists[i]))
    print(total)

我接受一個文件名並將line =中的所有對象設置為List。 然后,我創建一個變量total,它應該打印出列表中每個項目的總和。 例如,如果List = [1,2,3]則總數將為6.但是,是否可以將整數對象附加到列表中? 我收到的錯誤是......

File "/Users/sps329/Desktop/testss copy 2.py", line 10, in main
    total = sum(int(Lists[i]))
TypeError: list indices must be integers, not str

這樣的東西也不起作用,因為列表中的項目是字符串而不是數字。 我是否必須實現函數isdigit,即使我知道輸入文件將始終是整數?...

total = sum(i)
  1. 代替

     Lists = line 

    你需要

     Lists.append(line) 
  2. 你可以得到這樣的總和

     total = sum(sum(map(int, item)) for item in Lists) 
  3. 如果您不想創建列表列表,可以使用extend功能

     Lists.extend(line) ... total = sum(map(int, Lists)) 
# creates a list of the lines in the file and closes the file
with open(filename) as f:
    Lists = f.readlines()

# just in case, perhaps not necessary
Lists = [i.strip() for i in Lists]

# convert all elements of Lists to ints
int_list = [int(i) for i in Lists]

# sum elements of Lists
total = sum(int_list)
print sum([float(x.strip()) for x in open(filename)])  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM