简体   繁体   中英

Creating lists within a list Python

Given a list of integers A=[1,2,3,4,5,6,7,9] and a list p=[4,5,9] , how can I separate the values in A so that if they do not appear in p, they will be separated into a sub-list dictated by the position of the element of p in A. For example, in this case the output should be A=[[1, 2, 3], 4, 5, [6, 7, 8], 9].

s=25
# make it a string
s = str(s)

output = []
last = None

for c in A:
    if last is None:
        output.append(c)
    elif (last in s) == (c in s):
        output[-1] = output[-1] + c
    else:
        output.append(c)
    last = c

output # ['1', '2', '34', '5', '67']

This is a similar version of the problem that involves a list of strings.

Reference : Joining elements in Python list

You could do this by keeping track of all the elements found so far, and resetting the temporary list when you find an element in p :

A=[1,2,3,4,5,6,7,9]
p=[4,5,9]

def join_elements(A, p):
    curr = []
    for i in A: # Loop over possible values
        if i in p:
            if curr: # yield and reset current list
                yield curr 
                curr = []
            yield i # yield value from p 
        else: # Add to current list
            curr.append(i)
    if curr: # if we ended with an element that was not in p
        yield curr

print(list(join_elements(A, p)))

# [[1, 2, 3], 4, 5, [6, 7], 9]

Here you could find a general solution:

sub_list = [4, 5, 9]

temp = []
result = []
for i in range(1, 10):

    if i not in sub_list:
        temp.append(i)
        if temp not in result:
            result.append(temp)

    else:
        if len(temp) != 0:
            temp = []
        result.append(i)

print(result)



Output: [[1, 2, 3], 4, 5, [6, 7, 8], 9]

I believe this is what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM