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