【问题标题】:Creating lists within a list Python在列表 Python 中创建列表
【发布时间】:2020-01-21 17:26:22
【问题描述】:

给定一个整数列表 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

【问题讨论】:

  • 嘿,你有没有写过代码来尝试这个,我们可以看看?
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及重现它所需的最短代码在问题本身。没有明确问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.
  • 我在stackoverflow.com/questions/59813650/… 上看到了一个类似的问题,并有兴趣尝试这个想法
  • 如果你能展示你到目前为止所编码的内容,那将非常有帮助。在关闭之前编辑您的问题以包含它。

标签: python arrays python-3.x list


【解决方案1】:

您可以通过跟踪目前找到的所有元素来做到这一点,并在您在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]

【讨论】:

  • @Newbie123 更新了我的答案。
【解决方案2】:

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

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>

【讨论】:

  • 不应该是for i in A吗? (A 不保证是range(10))。此外,如果A 以不在p 中的元素结尾,则会失败。
  • 谢谢@rassar - 我做了一些更正,我相信它适用于所有类型的列表。如果还有改进的地方,请纠正我。
猜你喜欢
  • 2018-10-12
  • 2018-08-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
相关资源
最近更新 更多