用python中的交替元素创建新字符串

问题描述 投票:0回答:2

我需要创建一个新列表,其中包含之前两个列表中的交替元素。例如:listA =“ a”,“ b”,“ c”listB =“ A”,“ B”,“ C”输出应为“ a”,“ A”,“ b”,“ B”,“ c”,“ C”

def one_each(lst1,lst2):
        newList=[]
        for i in range(len(lst2)):
              newList.append(lst1[i])
              newList.append(lst2[i])
        return newList
python
2个回答
0
投票

尝试在两个列表之一的索引范围内使用单个循环,然后在每次迭代时从每个列表中追加一个元素。

def one_each(lst1, lst2):
    lst = []
    for i in range(0, len(lst1)):
        lst.append(lst1[i])
        lst.append(lst2[i])
    return lst

lst1 = ['a', 'b', 'c']
lst2 = ['A', 'B', 'C']

output = one_each(lst1, lst2)
print(output)

此打印:

['a', 'A', 'b', 'B', 'c', 'C']

0
投票

尝试这个:

def one_each(lst1,lst2):
  iRange=len(lst1)
  if len(lst2)<iRange:
    iRange=len(lst2)
  newList=[]
  for i in range(iRange):
        newList.append(lst1[i])
        newList.append(lst2[i])
  return newList

print (['a','b','c'],['A','B','C','D'])

输出:

['a', 'A', 'b', 'B', 'c', 'C', 'c']
© www.soinside.com 2019 - 2024. All rights reserved.