python 如何合并列表中的相似元素?

x6492ojm  于 2022-12-10  发布在  Python
关注(0)|答案(2)|浏览(131)

我正试着根据同行重新整理我的名单。
我有这样的清单:
['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_CURITIBA_A807_M-PRESS_HPA']
我想这样做:
['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']
元素“datetime”必须是列表中的第一个元素,但我想我可以在重新排序列表后这样做

hl0ma9xz

hl0ma9xz1#

完整代码

data = ['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM',
        'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']
data.remove("datetime") # removing datetime as it is the odd one in the list
data = sorted(data, key=lambda x: x.split("-")[-1])# sorting based on the last element ie. element after '-'
data.insert(0, "datetime") # Inserting the odd element 'datetime' back
print(data)

输出

['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']

希望这有帮助。快乐编码:)

fnvucqvd

fnvucqvd2#

如果最后一个“单词”以连字符为前缀,则:

indata = ['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_CURITIBA_A807_M-PRESS_HPA']

print([indata[0]] + sorted(indata[1:], key=lambda e: e.split('-')[-1]))

输出:

['datetime', 'INMET_BRASILIA_A001_M-DVENTO', 'INMET_CURITIBA_A807_M-DVENTO', 'INMET_BRASILIA_A001_M-PREC_MM', 'INMET_CURITIBA_A807_M-PREC_MM', 'INMET_BRASILIA_A001_M-PRESS_HPA', 'INMET_CURITIBA_A807_M-PRESS_HPA']

相关问题