在Python的列表列表中查找第一个元素的总和

时间:2019-02-17 12:29:27

标签: python list for-loop

newlist = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']....]

我有一个这样的清单。如何在子列表中添加第一个元素。

newlist[0][0] + newlist[1][0] + newlsit[2][0]...
# like 2.99+4.99+2.99+...

4 个答案:

答案 0 :(得分:4)

尝试一下:

request url: /foo/%23bar

正如@darksky所提到的,我将在这里进一步解释:

sum([float(i[0].replace('£','')) for i in a]) 将返回一个可迭代项的总和。

sum将字符串转换为float-> "2.99"

并且替换很明显。

输出将是:

2.99

答案 1 :(得分:3)

您可以使用生成器表达式,并在每个列表的第一个元素上sum(用[1:]对其进行切片以跳过£):

my_list = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'],
           ['£2.99', '1', '15-Feb-19']]


sum(float(l[0][1:]) for l in my_list)
# 10.97

答案 2 :(得分:2)

使用list comprehensions解决此问题:

l= [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']]

# 1. replace() will replace the first argument '£' with second argument (empty space).
# 2. map(): It takes two arguments, where first argument is the datatype 
#           you wish to convert to and second argument is value we want to convert.
# 3. list(): Since the list comprehension gives us the list of mapping, where as we need to 
#            convert it to proper proper list with numbers, and that's why we use list() 
#            to do so.
sum(list(map(float,[i[0].replace('£','') for i in l])))
    10.97

答案 3 :(得分:2)

这是一个不同的答案:

data = [['£2.99', '1', '16-Feb-19'], ['£4.99', '2', '16-Feb-19'], ['£2.99', '1', '15-Feb-19']]
sum = 0.0

for item in data:
    formatted = item[0][1:]
    sum += float(formatted)

该代码完成后,sum将等于结果10.97。