【发布时间】:2016-08-07 05:00:33
【问题描述】:
我的桌子:
New York 3 books 1000
London 2,25 2000
Paris 1.000 apples 3000
30 4000
Berlin newspapers
我想保留表格中的空字段,用xxxx 值填充它们并将整个表格放入一个列表中。
New York 3 books 1000
London 2,25 xxxx 2000
Paris 1.000 apples 3000
xxxx 30 xxxx 4000
Berlin xxxx newspapers xxxx
我所做的就是把每一行都捡起来并分开。
finallist = []
for line in range(1,6):
listtemp = re.split("\s{2,}", line)
finallist .append(listtemp)
然后我压缩了列表
zippedlist = zip(*finallist)
检查列的长度(现在是行)是否有足够的元素并添加缺少的元素xxxx 添加末尾,但这不起作用,因为它会压缩列(行拆分不会拾取空列中的空格)
我怎样才能用xxxx 元素填充表格并将它们放在这样的列表中:
[['New York','3','books','1000'],['London','2,25','xxxx','2000'],['Paris','1.000','apples','3000'],['xxxx','30','xxxx','4000'],['Berlin','xxxx','newspapers','xxxx']]
另一个表可能是:
New York 3 books 1000
London 2,25 2000
Paris 1.000 3000
30 4000
Berlin apples newspapers
更新
两个答案都没有给出解决方案,但我用两个都找到了不同的解决方案(经过大量尝试和尝试......)
#list of all lines
r = ['New York 3 books 1000 ', ' London 2,25 2000 ', ' Paris 1.000 3000 ', ' 30 4000 ', ' Berlin apples newspapers ']
#split list
separator = "\s{2,}"
mylist = []
for i in range(0,len(r)):
mylisttemp = re.split(separator, r[i].strip())
mylist.append(mylisttemp)
#search for column matches
p = regex.compile("^(?<=\s*)\S|(?<=\s{2,})\S")
i = []
for n in range(0,len(r)):
itemp = []
for m in p.finditer(r[n]):
itemp.append(m.start())
i.append(itemp)
#find out which matches are on next lines comparing the column match with all the matches of first line (the one with the smallest difference is the match).
i_currentcols = []
i_0_indexes = list(range(0,len(i[0])))
for n in range(1,len(mylist)):
if len(i[n]) == len(i[0]):
continue
else:
i_new = []
for b in range(0,len(i[n])):
difference = []
for c in range(0,len(i[0])): #first line is always correct
difference.append(abs(i[0][c]-i[n][b]))
i_new.append(difference.index(min(difference)))
i_notinside = sorted([elem for elem in i_0_indexes if elem not in i_new ], key=int)
#add linenr.
i_notinside.insert(0, str(n))
i_currentcols.append(i_notinside)
#insert missing fields in list
for n in range(0,len(i_currentcols)):
for i in range(1,len(i_currentcols[n])):
mylist[int(i_currentcols[n][0])].insert(i_currentcols[n][i], "xxxx")
【问题讨论】:
-
您的表格是您构建的文本文件吗?你能保证列长不会改变吗?你能按制表符分割行吗?
-
@Francesco,是的,它在一个文本文件中。列的长度并不总是相同的,它确实会发生变化。编号。列数和行数也是可变的。不,我不能按制表符拆分行。
-
你能假设列被至少两个连续的空格分隔吗?
标签: python list python-3.x split