List1 = [th,sk,is,bl] List2 = [ue,None,y,e]
输出=天空是蓝色的
合并两个给定列表,并合并它们的元素以获得所需的输出。
答案 0 :(得分:0)
嗨,您可以使用zip
并列出理解来完成该操作:
List1 = ['th','sk','is','bl']
List2=['ue',None,'y','e']
temp = list(zip(List1, List2[::-1]))
words = [i[0]+i[1] for i in temp]
words = [''.join(item for item in i if item) for i in temp]
" ".join(item for item in words)
List2[::-1]
将反转列表。
答案 1 :(得分:0)
这是我刚写的一些内容,不确定它是否是最Python的,但是这里有:
List1 = ["th","sk","is","bl"]
List2 = ["ue",None,"y","e"]
concat = ""
for i in range(len(List1)):
concat += List1[i]
if List2[len(List2)-1-i]: concat += List2[len(List2)-1-i]
concat += " "
print(concat)
预期输出:
the sky is blue
我得到:
>>> print(concat)
the sky is blue
>>>
但是如前所述,该站点的目的是教学而不是做。因此:
List1 = ["th","sk","is","bl"]
List2 = ["ue",None,"y","e"]
concat = ""
我们首先定义列表和“串联”变量,并在其中添加零件。
for i in range(len(List1)):
这适用于List1中的所有项目-我本来可以键入4,但这使得将来的扩展性变得容易。
concat += List1[i]
List1的顺序正确,数组从0开始。因此,首先我们有[0],第一个项目,到[3],最后一个项目。
if List2[len(List2)-1-i]: concat += List2[len(List2)-1-i]
由于List2中没有None,因此我们无法将NoneType连接到字符串。因此,我们测试它是否实际上是一个值(只需执行“ if string:”)。如果是这样,我们将其附加到我们的串联变量中。我之所以选择len(List2)-1-i:
List2长4 我们从i = 0
开始4-1-0 = 3
4-1-1 = 2
4-1-2 = 1
最后, 4-1-3 = 0
您会注意到,这些是我们在List1中使用的相同索引,但是向后是List2。
concat += “ “
我们在单词之间添加一个空格,最后;
print(concat)
我们打印出结果