Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - How to interleave two lists of different length?

I'm quite new to Python and I am still having a hard time actually using the language itself into my program. Here's what I have so far:

# 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?

Now the program is supposed to yield outputs like these:

outcome = twolists([ ], ['w', 'x', 'y', 'z'])
print(outcome)
['w', 'x', 'y', 'z']

outcome = twolists([0, 1], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x']

outcome = twolists([0, 1], ['w', 'x', 'y', 'z'])
print(outcome)
[0, 'w', 1, 'x', 'y', 'z']

outcome = twolists([0, 1, 2, 3], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x', 2, 3]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
def twolists(list1, list2):
    newlist = []
    a1 = len(list1)
    a2 = len(list2)

    for i in range(max(a1, a2)):
        if i < a1:
            newlist.append(list1[i])
        if i < a2:
            newlist.append(list2[i])

    return newlist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...