python - 在列表 Python 中创建列表

标签 python arrays python-3.x list

给定一个整数列表 A=[1,2,3,4,5,6,7,9]和一个列表 p=[4,5,9] ,我如何将 A 中的值分开,以便如果它们没有出现在 p 中,它们将被分成一个子列表,该子列表由 A 中 p 元素的位置决定。例如,在这种情况下,输出应该是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']

这是涉及字符串列表的问题的类似版本。

引用 :
Joining elements in Python list

最佳答案

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

关于python - 在列表 Python 中创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846305/

相关文章:

python - flask 虚拟环境

python - 将一系列分类数据转换为具有包含类别和新 id 的多索引的数据框

javascript - PHP 使用 javascript (codeigniter) 以动态形式进入数据库

python - 寻找 "decent"数字算法推理?

python - 检查另一个数据框中是否存在多行

python - 将 Tix 小部件添加到 Tkinter 容器

javascript - 如果 Obj 中存在数组,则获取数组项,如果不存在则获取字段

无法使用指针对没有临时变量的数组进行排序

python - 如何在 Flask 中获取 `request.form` 的数据?

python - matplotlib改变jpg图像颜色