Python 在列表中创建列表

Python 在列表中创建列表,python,arrays,python-3.x,list,Python,Arrays,Python 3.x,List,给定一个整数列表a=[1,2,3,4,5,6,7,9]和一个列表p=[4,5,9],我如何分离a中的值,以便如果它们不出现在p中,它们将被分离成一个子列表,由p元素在a中的位置决定。例如,在这种情况下,输出应该是a=[1,2,3],4,5,[6,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)

给定一个整数列表
a=[1,2,3,4,5,6,7,9]
和一个列表
p=[4,5,9]
,我如何分离a中的值,以便如果它们不出现在p中,它们将被分离成一个子列表,由p元素在a中的位置决定。例如,在这种情况下,输出应该是
a=[1,2,3],4,5,[6,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']
这是涉及字符串列表的问题的类似版本

参考:

在这里,您可以找到一个通用解决方案:

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]

我相信这就是您要查找的内容。

您可以跟踪到目前为止找到的所有元素,并在
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]

嘿,你有没有写过任何代码来尝试这个,我们可以看看?寻求调试帮助的问题(“为什么这个代码不工作?”)必须包括期望的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请看:我在上看到了一个类似的问题,我对这个想法很感兴趣。如果你能展示到目前为止你所编写的代码,这将非常有帮助。编辑您的问题,在结束之前将其包括在内。它不应该是A中的i的
?(
A
不保证是
范围(10)
)。此外,如果
A
结尾的元素不在
p
中,则此操作将失败。谢谢@rassar-我已经做了一些更正,我相信它适用于所有类型的列表。如果还有改进的余地,请纠正我。@Newbie123更新了我的答案。