Skip to main content
 首页 » 编程设计

python之寻找交换列表中项目的函数

2025年05月04日10shangdawei

我正在编写一个脚本来交换从 *.txt 文件读取的一些列表中的几个项目,我试着这样写:

i_file = map(lambda x: x.split('|'), open('test.txt', 'r').readlines()) 
for list in i_file: 
    list = [list[2], list[0], list[3], list[1], list[4:]] 
    #Actually I want to update the i_file, but I don't think this will work here 
    #nevermind, it's just a demostration. 

看起来很难看,很难看,所以我正在寻找

 somefunc() 

这可能会使我的代码看起来像这样。

i_file = map(lambda x: x.split('|').somefunc(), open('test.txt', 'r').readlines()) 

谢谢!!

更新:

输入文件如下所示:

blahblah1|3141593|Wednesday|John|BlahBlah1| 
blahblah2|2714323|Monday|Mike|BlahBlah2| 

我想在每一行中交换这些项目,以便将文件重写为:

3141593|Wednesday|blahblah1|John|BlahBlah1| 
blahblah2|Monday|2714323|Mike|BlahBlah2| 

请您参考如下方法:

Python 允许您分配给列表切片,因此您可以就地干净地置换列,而不会弄乱 lambda 和 map:

out = open("testout.txt", "w") 
 
for line in open('test.txt', 'r').readlines(): 
    lst = line.split("|") 
    lst[0:4] = lst[2], lst[0], lst[3], lst[1] 
    out.write("|".join(lst)) 

您甚至可以通过在赋值的一侧添加更多元素来插入或删除列:

>>> lst = "blahblah1|3141593|Wednesday|John|BlahBlah1|\n".split("|") 
>>> lst[0:4] = lst[2], lst[2][:3], lst[0], lst[3], lst[1] 
>>> print "|".join(lst) 
Wednesday|Wed|blahblah1|John|3141593|BlahBlah1|