给定一个整数列表A=[1,2,3,4,5,6,7,9]
和一个list p=[4,5,9]
,我如何分隔A中的值,以便如果它们不出现在p中,它们将被分成一个子列表,该子列表由p的元素在A中的位置决定。 ,在这种情况下,输出应为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']
这是涉及字符串列表的问题的类似版本。
您可以通过跟踪到目前为止找到的所有元素,并在以下位置找到元素时重置临时列表来做到这一点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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句