简体   繁体   English

列表清单,如何在每个列表中使用特定数字进行计算?

[英]List of lists, how can i do calculations with specific numbers in each list?

I have a function: 我有一个功能:

def readCSVfile(str1):

This function takes a CSV file that the user chooses and reads it. 此功能获取用户选择并读取的CSV文件。 Each file contains a list of list that looks like this: 每个文件包含一个列表列表,如下所示:

[[1, 1, 2.2, 1.3, 9.6], [1, 2, 2.1, 2.2, 7.6], [1, 3, 2.7, 1.5, 2.2], [2, 1, 3.0, 4.5, 1.5], [2, 2, 3.1, 3.1, 4.0], [2, 3, 2.5, 2.8, 3.0], [3, 1, 1.9, 1.8, 4.5], [3, 2, 1.1, 0.5, 2.3], [3, 3, 3.5, 2.0, 7.5], [4, 1, 2.9, 2.7, 3.2], [4, 2, 4.5, 4.8, 6.5], [4, 3, 1.2, 1.8, 2.7]]

Now, after the user have chosen a file the job is to make the program print out some calculations from each list made by my program but i am stuck. 现在,在用户选择文件后,工作就是使程序从我的程序所做的每个列表中打印出一些计算结果,但我陷于困境。 Say for example that i want to multiply the third and the fourth number in each list, how would i specify that? 比如说我想将每个列表中的第三个和第四个数字相乘,我将如何指定呢?

Trying to do something like 尝试做类似的事情

readCSVfile(str1)[2]

Don't work. 不要工作 I have googled like crazy 我像疯了一样谷歌搜索

through map and a lambda as one way:

li = [[1, 1, 2.2, 1.3, 9.6], [1, 2, 2.1, 2.2, 7.6], [1, 3, 2.7, 1.5, 2.2], [2, 1, 3.0, 4.5, 1.5], [2, 2, 3.1, 3.1, 4.0], [2, 3, 2.5, 2.8, 3.0], [3, 1, 1.9, 1.8, 4.5], [3, 2, 1.1, 0.5, 2.3], [3, 3, 3.5, 2.0, 7.5], [4, 1, 2.9, 2.7, 3.2], [4, 2, 4.5, 4.8, 6.5], [4, 3, 1.2, 1.8, 2.7]]

for el in map(lambda x: [x[0], x[1], round(x[2] * x[3],2),x[4]],li):
    print(el)

[1, 1, 2.86, 9.6]
[1, 2, 4.62, 7.6]
[1, 3, 4.05, 2.2]
[2, 1, 13.5, 1.5]
[2, 2, 9.61, 4.0]
[2, 3, 7.0, 3.0]
[3, 1, 3.42, 4.5]
[3, 2, 0.55, 2.3]
[3, 3, 7.0, 7.5]
[4, 1, 7.83, 3.2]
[4, 2, 21.6, 6.5]
[4, 3, 2.16, 2.7]
lst = [ [1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

for x in range(len(lst)):
    print(lst[x][2] * lst[x][3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM