【发布时间】:2020-07-30 18:45:50
【问题描述】:
我有一个列表,我需要根据两列按字母顺序排序。我当前的代码确实按字母顺序对其进行了排序,但上次也没有对人员进行排序。在我下面的代码中。我使用 itemgetter(3) 来获取人员的名字。但是我将如何做到这一点,以便我能够获得 2 个项目吸气剂,例如 itemgetter(3,4)。我希望我的问题是有意义的。谢谢。
注意:是否可以将名字和姓氏连接成一个字符串?然后使用那个字符串作为 item getter?
我的代码。
def sortAlpha():
newFile = open("ScriptTesting3.txt","w")
def csv_itemgetter(index, delimiter=' ', default=''):
def composite(row):
try:
return row.split(delimiter)[index]
except IndexError:
return default
return composite
with open("ScriptTesting2.txt", "r") as file:
for eachline in sorted(file, key=csv_itemgetter(3)):
print(eachline.strip("\n") , file = newFile)
ScriptTesting2.txt
2312 filand 4 Joe Alex
4541 portlant 4 Alex Gray
5551 highlands 4 Alex Martin
我的输出
5551 highlands 4 Alex Martin
4541 portlant 4 Alex Gray
2312 filand 4 Joe Alex
输出应该是
5551 highlands 4 Alex Gray
4541 portlant 4 Alex Martin
2312 filand 4 Joe Alex
【问题讨论】:
-
你可以在问题中添加文本文件的内容吗?
-
@Anand 我刚刚做了。
标签: python csv sorting alphabetical