[英]How to split string at index[0] of each sublist, and have each split index in it's own original list?
How could you split a string at index 0 of all sublists into separate elements, and have each of the split elements be contained within a copy of the original sublist? 如何将所有子列表的索引0处的字符串拆分为单独的元素,并将每个拆分元素包含在原始子列表的副本中?
For example: 例如:
Original_List = [['a,b','c','d','e','f'],['1','2','3'],['z,y','1','2']]
Desired Result: 期望的结果:
Desired_List = [['a','c','d','e','f'],['b','c','d','e','f'],['1','2','3'],['z','1','2'],['y','1','2']]
Also, to add further clarity with one more actual example: 此外,为了进一步明确一个更实际的例子:
Original_List = [['Contract_ID1,Contract_ID2','Amount','Date'],['Contract_ID3,Contract_ID4','400','Jan1']]
I want every sublist to have only one Contract_ID, but still have the Amount and Date Associated with it 我希望每个子列表只有一个Contract_ID,但仍然具有与之关联的金额和日期
Desired_List = [['Contract_ID1','Amount','Date'],['Contract_ID2','Amount','Date'],['Contract_ID3','400','Jan1'],['Contract_ID4','400','Jan1']]
I can split all strings at index 0 of all sublists with the below, but I can't figure out how I would duplicate the whole list for each split element and then replace the strings that were split with the split element, so that each split element had its own list. 我可以用下面的方法拆分所有子列表的索引0处的所有字符串,但我无法弄清楚如何为每个拆分元素复制整个列表,然后替换用split元素拆分的字符串,以便每个拆分element有自己的列表。
Split_First_Indices_of_Sublists = map(lambda x: x[0].split(","),Original_List)
>>[['a', 'b'], ['1'], ['z', 'y']]
for x in Original_List:
x.pop(0)
>> [['c', 'd', 'e', 'f'], ['2', '3'], ['1', 2]]
I think it's clearest written out as explicit loops: 我认为它最清楚地写成显式循环:
Desired_List = []
for li in Original_List:
for spl in li[0].split(','):
Desired_List.append([spl] + li[1:])
gives: 得到:
Desired_List
Out[153]:
[['a', 'c', 'd', 'e', 'f'],
['b', 'c', 'd', 'e', 'f'],
['1', '2', '3'],
['z', '1', '2'],
['y', '1', '2']]
And of course you can immediately turn this into the equivalent one-line list comp: 当然,您可以立即将其转换为等效的单行列表comp:
[[spl] + li[1:] for li in Original_List for spl in li[0].split(',')]
Which may or may not be less readable, depending on the reader :-) 根据读者的不同,哪些可能或不具有可读性:-)
And as a last note, make sure that this is the data structure you really want. 最后一点,请确保这是您真正想要的数据结构。 A
dict
keyed by Contract_ID
seems like a very natural structure for your end product. Contract_ID
键入的dict
似乎是您最终产品的非常自然的结构。
Original_List=[['a,b','c','d','e','f'],['1','2','3'],['z,y','1','2']]
desired_list=[]
for p in pl:
try:
splited=p.split(',')
if not type(splited) is list:
splited=[splited]
if count(splited)>1:
for list in splited:
p[0]=list
desired_list.append(p)
else:
desired_list.append()
except:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.