Home > database >  Make list of list from specific str
Make list of list from specific str

Time:12-07

I have a big list and looks like:

a=["cos","3","4","5","cos1","4","5","cos2","1"]

I would like create a list of list similar to:

a=[["cos","3","4","5"],["cos1","4","5"],["cos2","1"]]

I tried

sub=[]
for i,y in enumerate(a):
     if "cos" in y:
         sub.append([y])
         continue

It didn't work. Could you help me?

CodePudding user response:

You're close to getting what you want. As it stands, you only create a new sub-list if "cos" is a part of the string you're currently looking at. What about when "cos" isn't in that string?

Right now, you just ignore this case. However, you want to add this element to the sub-list that you previously appended to sub. You can access the sub-list as sub[-1] because it's the last element of sub, and then append to it.

sub=[]
for y in a:
     if "cos" in y:
         sub.append([y])
     else:
         sub[-1].append(y)

Which gives

sub =  [['cos', '3', '4', '5'], ['cos1', '4', '5'], ['cos2', '1']]

I removed the unnecessary enumerate() and continue.

This assumes that the first element of a contains "cos", so that sub[-1] will always exist when that line is executed. Handling the error when this isn't the case is left as an exercise for the reader.

CodePudding user response:

Watch for the occurrences of the 'cos'. If you encounter numbers, you just add them to the temporary list. When you encounter the name 'cos', you should add the temp list(your sublist) to the result list Also create a new temp list which starts with the item has 'cos'.

But there is an exception in the first iteration, you don't want to add empty list to the result(because you encounter 'cos' but the temp is empty). So if temp: is for that.

If you do not want this extra if condition, and if your list begins with 'cos', you can have temp = [a[0]] at the beginning and then iterate through the rest of the items.

a = ["cos", "3", "4", "5", "cos1", "4", "5", "cos2", "1"]

res = []
temp = []
for item in a:
    if not item.startswith('cos'):
        temp.append(item)
    else:
        if temp:
            res.append(temp)
        temp = [item]

if temp:
    res.append(temp)
print(res)

output:

[['cos', '3', '4', '5'], ['cos1', '4', '5'], ['cos2', '1']]
  • Related