首页 > 解决方案 > 按相同索引对列表python进行排序

问题描述

我正在尝试对数组中的数据进行排序。我的 python 代码给出以下输出:

Value List: [['house'], ["'tW'"], ['6.998332153088995']]
Insert at array index: 3
[['6.998332153088995']]


Value List: [['house'], ["'Total'"], ['91.40121710449374']]
Insert at array index: 11
[['91.40121710449374']]


Value List: [['garden'], ["'flower'"], ['0.1525635807425692']]
Insert at array index: 0
[['0.1525635807425692']]


Value List: [['garden'], ["'gras'"], ['0.31921114287979435']]
Insert at array index: 12
[['0.31921114287979435']]

现在我想将这些值写入 .txt 文件,但我想按以下方式对它们进行排序:

#region tW     Total    flower    gras
house   6.9983 91.40121
garden                  0.152     0.312

这意味着值列表的第一项停留在开头,并用特定位置的值填充。但我不想有双重条目,例如房子,房子应该只有一行。

但不幸的是 list.insert(position, value) 在我的情况下不起作用。我现在在这里为您提供我给我上述输出的最小代码:

newarraylist = []
print("Value List: " + str(list4))
print("Insert at array index: " + str(save_values_to_file(list4)))
newarraylist.insert(save_values_to_file(list4), list4[2])
print(newarraylist)

希望有人可以帮助我解决初学者的问题

标签: pythonlist

解决方案


做起来很棘手,但这里有一些可行的方法。首先,我将您的数据(因此我的问题)格式化为 Python 格式:列表列表。这有点麻烦,因为每个数据元素都是它自己的列表,但就这样吧:

lsts=[
[['house'], ["'tW'"], ['6.998332153088995']],
[['house'], ["'Total'"], ['91.40121710449374']],
[['garden'], ["'flower'"], ['0.1525635807425692']],
[['garden'], ["'gras'"], ['0.31921114287979435']]
]

这个想法是使用标题列表来计算有多少不同的“属性”,并为“区域”使用字典,用足够的空字符串初始化以适应所有属性。

headers = [lst[1][0] for lst in lsts]                           # a list with the headers ['tW', 'Total', 'flower', 'gras']
regions = set([lst[0][0] for lst in lsts])                      # a set of the regions: {'house', 'garden'}
valdict = {region:len(headers) * [''] for region in regions}    # a dict: {region:['', '', '', ''], } where the list has the same number of items as the header list

for lst in lsts:
    valdict[lst[0][0]][headers.index(lst[1][0])] = lst[2][0]    # in the dict, change one of the empty list items

输出部分首先打印变量,然后将所有内容打印为表格:

# RAW OUTPUT
print(headers)
for region, values in valdict.items():
    print(region, values)

#PRETTY PRINT (a bit clumsy, but it shows a nice table format
print('\nPretty print\n')

print('{:10}'.format(''), end='')
for header in headers:
    print('{:10}'.format(header), end='')
for region in regions:
    print('\n{:10}'.format(region), end='')
    for val in valdict[region]:
        if val == '':
            print('{:<10}'.format(val), end='')                 # print empty strings in list
        else:
            print('{:<10.4f}'.format(float(val)), end='')       # format print strings as floats

最终输出

["'tW'", "'Total'", "'flower'", "'gras'"]
garden ['', '', '0.1525635807425692', '0.31921114287979435']
house ['6.998332153088995', '91.40121710449374', '', '']

Pretty print

          'tW'      'Total'   'flower'  'gras'
garden                        0.1526    0.3192
house     6.9983    91.4012

唯一的问题是,因为我使用了一个字典,所以gardenand的顺序house是不确定的。当然,您可以对 dict 进行排序,也可以使用它SortedDict来进一步塑造数据。

PS:我对更优雅的解决方案持开放态度;-)


推荐阅读