我想输入一个列表输入(可以有多种长度),并创建新列表,将每个潜在的连续对连接起来。
例如:
mylist = ['07', '05', '66', '06755', '04']
返回如下:
['0705', '66', '06755', '04']
['07', '0566', '06755', '04']
['07', '05', '6606755', '04']
['07', '05', '66', '0675504']
我已经在下面编写了代码,但我希望有更好的方法,因为我担心切片会遇到问题。
def joinConsecutive(nums):
parts = len(nums)
newNums = []
# Join 1st and 2nd parts
merge1 = [''.join(nums[0:2])] + nums[2:]
newNums.append(merge1)
# Join 2nd and 3rd parts, etc.
i = 1
while i <= parts - 2:
start = nums[0:i]
mid = [''.join(nums[i:i+2])]
# When joining 2nd-to-last and last parts, this end just gets ignored
end = nums[i+2:]
newNums.append(start + mid + end)
i += 1
return newNums
joinConsecutive(mylist)
[['0705', '66', '06755', '04'],
['07', '0566', '06755', '04'],
['07', '05', '6606755', '04'],
['07', '05', '66', '0675504']]
答案 0 :(得分:3)
使用一些索引数学和嵌套列表理解:
>>> [mylist[:i] + [mylist[i]+mylist[i+1]] + mylist[i+2:] for i in range(len(mylist)-1)]
[['0705', '66', '06755', '04'], ['07', '0566', '06755', '04'], ['07', '05', '6606755', '04'], ['07', '05', '66', '0675504']]
不用担心“切片问题”,因为Python会自动为您处理超出范围的切片索引(通过返回一个空列表)。
答案 1 :(得分:1)
我认为您的方法很好(切片永远不会引发IndexError
,而是返回空列表)。
不过,您可以使用try / except并枚举来提高可读性:
def join_consecutive_values(mylist):
result = []
for i, value in enumerate(mylist):
try:
merged_value = value + mylist[i+1]
except IndexError: # we're done!
break
new_list = mylist[:i] + [merged_value] + mylist[i+2:]
result.append(new_list)
return result
答案 2 :(得分:0)
def joinConsecutive(mylist):
output=[]
for i,val in enumerate(mylist[:-1]):
newlist=mylist.copy()
newlist[i]=val+newlist.pop(i+1)
output.append(newlist)
return(output)
joinConsecutive(mylist)
[['0705', '66', '06755', '04'],
['07', '0566', '06755', '04'],
['07', '05', '6606755', '04'],
['07', '05', '66', '0675504']]
答案 3 :(得分:0)
尝试一下:
def joinConsecutive(nums):
newNums = []
for i in range(len(nums) - 1):
tmp = nums.copy()
tmp[i] = tmp[i] + tmp[i + 1]
tmp.pop(i + 1)
newNums.append(tmp)
return newNums