123|china|jack|342|usa|Nick|324345|spin|Amy
我想要这样的最终结果(我知道每3个元素需要一个新行):
123,china,jack
342,usa,Nick
324345,spin,Amy
谢谢
答案 0 :(得分:2)
试试:
x = '123|china|jack|342|usa|Nick|324345|spin|Amy'
l = x.split('|')
new_l = [l[i:i+3] for i in range(0,len(l),3)]
这会给你:
>>> for i in new_l:
... print ','.join(i)
...
123,china,jack
342,usa,Nick
324345,spin,Amy
更新:阅读文件
要将文件作为字符串读取,请执行以下操作:
with open('your_file.txt', 'r') as myfile:
x=myfile.read().replace('\n', '|')
答案 1 :(得分:1)
可以使用一个print
语句
>>> d = '123|china|jack|342|usa|Nick|324345|spin|Amy'
>>> l = d.split('|')
>>> print(*list(map(lambda v: ','.join(v),[l[x: x+3] for x in range(0, len(l), 3)])), sep='\n')
123,china,jack
342,usa,Nick
324345,spin,Amy
所以现在一步一步
>>> d = '123|china|jack|342|usa|Nick|324345|spin|Amy'
>>> l = d.split('|') # splitting input string into list of str objects that separated with '|'
>>> l
['123', 'china', 'jack', '342', 'usa', 'Nick', '324345', 'spin', 'Amy']
>>> [l[x: x+3] for x in range(0, len(l), 3)] # combining elements by 3
[['123', 'china', 'jack'], ['342', 'usa', 'Nick'], ['324345', 'spin', 'Amy']]
>>> list(map(lambda v: ','.join(v),[l[x: x+3] for x in range(0, len(l), 3)])) # merging every sublist to str with ',' as separator
['123,china,jack', '342,usa,Nick', '324345,spin,Amy']
>>> print(*list(map(lambda v: ','.join(v),[l[x: x+3] for x in range(0, len(l), 3)])), sep='\n') # final print
123,china,jack
342,usa,Nick
324345,spin,Amy