如何根据 Python 中的值拆分列表?

How to split list based on values in Python?

我有一个列表需要复制乘以索引处的数字。 这里有一个例子来帮助解释。

原榜单:

[AAA, Bus, Apple, 5, 3, 1, Car, 22, 30]

需要变成什么:

aList = [
[AAA, Bus, Apple, 1, 1, 1, Car, 22, 30]
[AAA, Bus, Apple, 1, 1, 0, Car, 22, 30]
[AAA, Bus, Apple, 1, 1, 0, Car, 22, 30]
[AAA, Bus, Apple, 1, 0, 0, Car, 22, 30]
[AAA, Bus, Apple, 1, 0, 0, Car, 22, 30]
]

所有列表都按相同的顺序排列,以便我可以查看索引值。 谢谢

希望我没听错你的问题。此示例将按列表中找到的最大数量复制列表:

lst = ["AAA", "Bus", "Apple", 5, 3, 1, "Car"]

n = max((v for v in lst if isinstance(v, int)), default=0)

out = [lst]
for _ in range(n - 1):
    out.append([(v - 1) if isinstance(v, int) else v for v in out[-1]])

out = [[int(v > 0) if isinstance(v, int) else v for v in l] for l in out]

print(*out, sep="\n")

打印:

['AAA', 'Bus', 'Apple', 1, 1, 1, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']

编辑:仅更改指定的索引:

lst = ["AAA", "Bus", "Apple", 5, 3, 1, "Car"]

n = max(v for v in lst[3:6])

out = [lst[3:6]]
for _ in range(n - 1):
    out.append([v - 1 for v in out[-1]])

out = [lst[:3] + [int(v > 0) for v in l] + lst[6:] for l in out]

print(*out, sep="\n")

打印:

['AAA', 'Bus', 'Apple', 1, 1, 1, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 1, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']
['AAA', 'Bus', 'Apple', 1, 0, 0, 'Car']