首页 > 解决方案 > 如何在python的4列列表中获取前两列的最小值和后两列的最大值?

问题描述

例如,从下面的数据 -

A  B  C  D         
30 10 20 8
30  5 20 20
20 10 30 10

我需要知道[20,5,30,20]A、B、C、D 是列名的位置。我不能使用熊猫。

标签: python

解决方案


我知道你已经有了一些答案。这是另一个,但对于 python 新手来说可能很容易。我也尝试先用最简单的方法来做,然后使用更高级的语法来更快地完成工作。

我不确定您的数据是如何存储的。我将把你的输入存储到一个字符串中,并在这个例子中处理这个字符串。

在此示例中,我将使用列表推导,如果您不熟悉此概念,请查看我共享的链接。

data = '''A.      B.         C.    D.         
30     10          20    8
30     5           20    20
20     10          30    10'''

#first split the string into a list
rows = data.split('\n')

#define a dictionary to store the values from the rows
dict_list = {'A':[],'B':[],'C':[],'D':[]}

#final values will be stored into the min_list
min_list = []

#next break each item from the row into a list of values
row_items = [i.split() for i in rows[1:]]

#add each item from the row as elements into a dictionary
for each_row in row_items:
    dict_list['A'].append(int(each_row[0]))
    dict_list['B'].append(int(each_row[1]))
    dict_list['C'].append(int(each_row[2]))
    dict_list['D'].append(int(each_row[3]))

#iterate through the dictionary to get the min value for each key
for k,v in dict_list.items():
    min_list.append(min(v))

print ('minimum of each col :', min_list)

其输出将是:

minimum of each col : [20, 5, 20, 8]

另一种方法是使用一些列表推导和 zip 函数 类似于列表推导,如果您不熟悉 zip 函数,请使用此链接。

#first split the string into a list
rows = data.split('\n')
#next break each item from the row into a list of values
row_items = [i.split() for i in rows[1:]]

#convert the row_items into integers
row_int_items = [[int(x) for x in row_item] for row_item in row_items ]

#transpose the list from rows to columns
col_items = list(zip(*row_int_items))

min_list = [min(x) for x in col_items]

print ('items by each row   :', row_int_items)
print ('items by each col   :', col_items)
print ('minimum of each col :', min_list)

第二个示例的输出如下:

items by each row   : [[30, 10, 20, 8], [30, 5, 20, 20], [20, 10, 30, 10]]
items by each col   : [(30, 30, 20), (10, 5, 10), (20, 20, 30), (8, 20, 10)]
minimum of each col : [20, 5, 20, 8]

推荐阅读