我想知道是否有可能在列表列表中获得每个列表的最小值。
import csv
data=[]
file=input ("Enter file name: ")
with open(file,"r") as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
data.append(row)
print(data)
输出:
[['13.25', '12.97', '13.12', '13.47', '13.44', '13.09', '12.86', '12.78', '12.91', '12.93', '12.91', '13.11'], ['12.92', '13.42', '13.58', '13.7', '13.62', '13.7', '13.31', '12.86', '12.59', '12.81', '13.46', '12.9'], ['13.39', '13.5', '13.29', '13.26', '13.38', '13.45', '13.46', '11.95', '', '12.57', '13.22', '12.88'], ['12.48', '13.76', '13.7', '13.77', '13.08', '13.48', '13.25', '12.31', '12.56', '12.56', '12.95', '13.38'], ['12.52', '14.07', '14.46', '14.13', '13.98', '14.07', '13.92', '12.7', '13.01', '12.79', '13', '13.13']]
答案 0 :(得分:3)
通过简单调用map
即可实现数字列表列表的最小值:
numbers = [[1,3,6], [6,7,2], [0,-4]]
minimum_numbers = map(min, numbers)
print minimum_numbers
# This prints: [1, 2, -4]
这将返回一个列表,其中为{"外部列表"中的每个元素调用了min
。 numbers
。
答案 1 :(得分:2)
Python有一个min函数,可以在列表上调用以获得最低值。您可以遍历data
列表,并在包含的每个列表中调用min()
。
for list in data:
print(min(list))
鉴于你的输出,这将返回:
12.78
12.59
12.31
12.52
第三个是空白的,因为数组中有一个空值。
如果要删除空字符串,可以使用filter()
for list in data:
list = filter(None, list)
print(min(list))
此输出
12.78
12.59
11.95
12.31
12.52
另外我注意到所有的值都是浮点数,你也可以在检查最小值之前转换它们,这样你就不会比较字符串。
for list in data:
list = filter(None, list)
list = [float(i) for i in list]
print(min(list))
答案 2 :(得分:1)
首先,您需要将每个项目转换为浮点数。当您阅读以下数据时执行此操作:
import csv
data=[]
file=input ("Enter file name: ")
with open(file,"r") as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
data.append([float(x) for x in row if x]) # converts values to floats, ignores empty ones
print(data)
完成后,只需在每个列表上调用min()
:
>>> [min(x) for x in data]
[12.78, 12.59, 11.95, 12.31, 12.52]
您可以缩短阅读循环:
>>> with open(file, "r") as f:
... reader = csv.reader(f, delimiter=";")
... data = [[float(x) for x in row] for row in reader]
>>> print([min(x) for x in data])
答案 3 :(得分:0)
我认为您应该使用Emil Vikström's answer,但由于您可以控制加载代码,因此可以防止不必要的数据存储,只需执行以下操作:
with open(file,"r") as f:
reader = csv.reader(f, delimiter=';')
for row in reader:
data.append(min(map(float, row)))
答案 4 :(得分:-1)
我会使用地图功能......
listOfLists = [ [2, 3, 1], [5, 7, 8], .... ]
minValues = map(lambda x: min(x), listOfLists)
Result:
minValues = [1, 5, ...]