相关疑难解决方法(0)

Pythonic方式以交替的方式组合两个列表?

我有两个列表,第一个列表保证只包含一个列表而不是第二个列表.我想知道创建一个新列表的最Pythonic方法,其中偶数索引值来自第一个列表,其奇数索引值来自第二个列表.

# example inputs
list1 = ['f', 'o', 'o']
list2 = ['hello', 'world']

# desired output
['f', 'hello', 'o', 'world', 'o']
Run Code Online (Sandbox Code Playgroud)

这有效,但并不漂亮:

list3 = []
while True:
    try:
        list3.append(list1.pop(0))
        list3.append(list2.pop(0))
    except IndexError:
        break
Run Code Online (Sandbox Code Playgroud)

如何实现这一目标呢?什么是最Pythonic方法?

python

75
推荐指数
8
解决办法
5万
查看次数

如何交错两个不同长度的列表?

我是Python的新手,我仍然很难将语言本身用于我的程序.这是我到目前为止所拥有的:

# Purpose: 'twolists' = takes 2 lists, & returns a new list containing
# alternating elements of lists. 
# Return = final_list
# Parameter = list1, list2

def twolists(list1, list2): # don't forget to return final_list
    alt_list = []
    a1 = len(list1)
    a2 = len(list2)

    for i in range(# ? ):
        # append one thing from list1 to alt_list - How?
        # append one thing from list2 to alt_list - How?
Run Code Online (Sandbox Code Playgroud)

现在该程序应该产生如下输出:

outcome = twolists([ ], ['w', 'x', 'y', …
Run Code Online (Sandbox Code Playgroud)

python

5
推荐指数
2
解决办法
1695
查看次数

标签 统计

python ×2