我正在编写一个脚本来交换从* .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|
答案 0 :(得分:3)
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|
答案 1 :(得分:2)
一种通用方法是将索引和列表分开:
>>> parts = range(7)
>>> indices = [2, 0, 3, 1] + range(4, 7)
>>> [parts[i] for i in indices]
[2, 0, 3, 1, 4, 5, 6]
答案 2 :(得分:1)
我只想做以下事情:
i_file = map(lambda x: x.split('|'), open('test.txt', 'r').readlines())
for l in i_file:
l[:] = [l[2], l[0], l[3], l[1]] + l[4:]
注意:
[:]
,此代码将更新i_file
。 list
,因此不会影响builtin。l[4:]
被列入子列表。答案 3 :(得分:1)
您可以将列表解压缩为单独的值,然后以不同的顺序重新组合:
>>> a, b, c = [1, 2, 3]
>>> [a, c, b]
[1, 3, 2]
所以对于你的代码:
>>> line = 'blahblah1|3141593|Wednesday|John|BlahBlah1|'
>>> blah, number, day, name, other_name, empty = line.split('|')
>>> '|'.join([number, day, blah, name, other_name, empty])
'3141593|Wednesday|blahblah1|John|BlahBlah1|'
或者您可以使用regular expression:
>>> import re
>>> line = 'blahblah1|3141593|Wednesday|John|BlahBlah1|'
>>> match = re.match(r'(.*)\|(.*)\|(.*)\|(.*)\|(.*)\|', line)
>>> match.expand(r'\2|\3|\1|\4|\5|')
'3141593|Wednesday|blahblah1|John|BlahBlah1|'
注意:我不是re
的专家,可能有更好的方法。
答案 4 :(得分:1)
执行所需操作的功能是operator.itemgetter
:
>>> lines = ["blahblah1|3141593|Wednesday|John|BlahBlah1|",
... "blahblah2|2714323|Monday|Mike|BlahBlah2|"]
>>> swap = operator.itemgetter(2, 0, 3, 1, slice(4,None))
>>> map(lambda x: swap(x.split('|')), lines)
[('Wednesday', 'blahblah1', 'John', '3141593', ['BlahBlah1', '']), ('Monday', 'b
lahblah2', 'Mike', '2714323', ['BlahBlah2', ''])]
答案 5 :(得分:1)
如果您坚持使用lambda
和map
map(lambda x: (lambda a,b,c,d,*e: list((c,a,d,b) + e))(*x.split('|')), open('test.txt', 'r').readlines())
答案 6 :(得分:0)
您可以嵌套列表推导以获得您想要的内容。这样的事情应该可以解决问题。 (另)
i_file = [ [ y[2], y[0], y[3], y[1] ] + y[4:] for y in [ x.split('|') for x in open('test.txt','r').readlines() ] ]