Home > Software design >  How to combine/merge a number list and a string list into a new list in ascending order in python us
How to combine/merge a number list and a string list into a new list in ascending order in python us

Time:09-22

I want to combine a number list and a string list in ascending order.

Example a = [1, 2, 3], b = [a, b, c, d]

combine a and b and the answer should be [1, a, 2, b, 3, c, d]

or a = [1,2,3], b = [b, d]

combine a and b and the answer should be [1, 2, b, 3, d]

def combine(a, b):
a = [str(int) for int in a]
b = [str(int) for int in b]
if a and b:
    if a[0] > b[0]:
        a, b = b, a
    return [a[0]]   combine(a[1:], b)
return a   b

a = [1, 2, 3] b = ['a', 'b', 'c', 'd']

combine(a, b)

But I got this

['1', '2', '3', 'a', 'b', 'c', 'd']

CodePudding user response:

a = [1, 2, 3]
b = ["a", "b", "c", "d"]
new = []
for i in range(max(len(a), len(b))):
    if len(a) > i:
        new.append(a[i])
    if len(b) > i:
        new.append(b[i])

CodePudding user response:

Used recursion:

def combine(nums, lets):
    if not nums or not lets:
        return nums   lets
    res = []
    counts = [0, 0]
    num = nums[0]
    let = ord(lets[0]) - 96
    if num <= let:
        counts[0]  = 1
        res.append(nums[0])
    if num >= let:
        counts[1]  = 1
        res.append(lets[0])
    return res   combine(nums[counts[0]:], lets[counts[1]:])


if __name__ == '__main__':
    nums = [1, 2, 3, 4]
    lets = ['b', 'c', 'd']
    print([str(i) for i in combine(nums, lets)])

CodePudding user response:

Are you looking to sort a, b, c... based on their position in the alphabet?

from string import ascii_lowercase
combined_list = [1, 2, 3]   ["a", "b", "c", "d"]
combined_list.sort(key=lambda elem: elem if type(elem) is int else ascii_lowercase.index(elem)   1)

If thats the case, maybe you want to consider creating your own sorting logic (1, "a", 2, "b"...) first and use that.

  • Related