0

I want to combine a number list and a string list

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, b, 2, d, 3]

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']

joule.v
  • 5
  • 2
  • 1
    Looking at your examples, it is not clear what you mean by "in ascending order". How is ```[1, 2, 'b', 3, 'd']``` the combination of ```[1,2,3]``` and ```['b', 'd']``` in ascending order? – BernieD Sep 21 '22 at 20:34
  • if you want ascending order, just `result = list(sorted(a + b))` – Matiiss Sep 21 '22 at 20:37

3 Answers3

1

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)])
Inozem
  • 183
  • 1
  • 1
  • 8
0
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])
Elicon
  • 206
  • 1
  • 11
  • 1
    That doesn't work for the second example. But the desired rule to sort the new list is not really clear in the question. – BernieD Sep 21 '22 at 20:36
  • Thank you @BernieD Sorry for not explicit clear. but your code is correct. You saved the day – joule.v Sep 21 '22 at 22:31
0

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.

bitflip
  • 3,436
  • 1
  • 3
  • 22