0

I have two lists and I want to create one list containing its data.

ls1 = ["1","2","3","4"]

ls2 = ["4","3","2","1"]

The answer I am looking for is of this form....

ls3 = ["1-4","2-3","3-2","4-1"]

Is there any possibility of achieving this? Note the minus sign between the numbers.

1
  • 1
    Any reason why you're looking to do this? Commented Jan 5, 2015 at 23:51

3 Answers 3

7
>>> ls3 = ['-'.join(x) for x in zip(ls1, ls2)]
['1-4', '2-3', '3-2', '4-1']
Sign up to request clarification or add additional context in comments.

Comments

2

So @aesthete's answer is right. I just want to add explanation.

>>> ls3 = ['-'.join(x) for x in zip(ls1, ls2)]
['1-4', '2-3', '3-2', '4-1']

the [someaction(x) for x in somelist] will return a list where each element is someaction() performed on the corresponding x in somelist. This is called a list comprehension.

In this case somelist is zip(ls1,ls2) which creates [(ls1[0], ls2[0]), (ls1[1], ls2[1]), ...]

So zip(ls1,ls2) returns [('1', '4'), ('2', '3'), ('3', '2'), ('4', '1')]

The someaction() is '-'.join() What that does is it takes a iterable sequence of strings and joins them together with the string '-' in between. So you could have done ' to '.join(x) to get ['1 to 4', '2 to 3', ...]

Comments

2
>>> [ "{}-{}".format(ls1[x],ls2[x]) for x in range(len(ls1))]
['1-4', '2-3', '3-2', '4-1']

using map:

>>> map("{}-{}".format,ls1,ls2)
['1-4', '2-3', '3-2', '4-1']

using itertools.strmap:

>>> list(itertools.starmap("{}-{}".format,zip(ls1,ls2)))
['1-4', '2-3', '3-2', '4-1']

3 Comments

This is creative. map('{}-{}'.format, ls1, ls2) would make this idea look really good
yep this is alo nice list(itertools.starmap("{}-{}".format,zip(ls1,ls2))) ['1-4', '2-3', '3-2', '4-1']
I've never been able to find a good use for starmap in my life, i don't think that is a good use either

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.