-
万千封印
main.pya = ['A', 'B', 'C', 'D', 'E']b = [i + j for i, j in zip(a[:-1:2], a[1::2])]if len(a) % 2 == 1: b.append(a[-1])print(b)结果$ python main.py['AB', 'CD', 'E']
-
汪汪一只猫
>>> [''.join(a[i:i+2]) for i in range(0, len(a), 2)]['AB', 'CD', 'E']或者(因为我喜欢迭代器)>>> it = iter(a)>>> [s + next(it, '') for s in it]['AB', 'CD', 'E']
-
MYYA
我认为更简单的方法是迭代数组并连接字符,如果您有偶数长度的数组,它就可以工作,因此您可以添加检查并在奇数长度的情况下附加最后一个元素。array = ['A', 'B', 'C', 'D', 'E']array2 = [f"{array[i]}{array[i+1]}" for i in range(0, len(array)-1, 2)]if len(array)%2!=0: array2.append(array[-1])print(array2)
-
扬帆大鱼
尝试这样。这是非常简单的答案,但应该有效。my_array = ['A', 'B', 'C', 'D', 'E']def combine_array(my_array): mixed_array = [] start_new = True for item in my_array: if start_new: mixed_array.append(item) start_new = False else: mixed_array[-1] = mixed_array[-1] + item start_new = True return mixed_arrayif __name__ == "__main__": try: print(combine_array(my_array)) except Exception as err: print(err)
-
呼如林
startArray = ['A', 'B', 'C', 'D', 'E']currentIndex = 0finishArray = ['']for x in startArray: if len(finishArray[currentIndex]) == 2: currentIndex += 1 finishArray.insert(currentIndex,x) else: finishArray[currentIndex] += xprint(finishArray)