eagertoLearn
eagertoLearn

Reputation: 10162

condensing the code or a one liner possible for this code in python

I have the following code and wondering if there is a simpler way to do this. I am creating a list of tuples that holds letters from a string and the corresponding number from a list. here it is

s="hello"
lst=[1,2,3,4,5]
res = []
for i in range(len(lst)):
    res.append((s[i],lst[i]))
print res

The output is here which is correct. I am looking for condensed version if possible

[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]

Upvotes: 0

Views: 142

Answers (4)

Corley Brigman
Corley Brigman

Reputation: 12401

i don't know if the list is always just monotonic numbers, but if they are, you can either replace it with range(), or use enumerate to make this one line:

s = 'hello'
sd = dict([reversed(x) for x in enumerate(s)])

s = 'hello'
zip(s, xrange(len(s)))

Upvotes: 2

brain storm
brain storm

Reputation: 31262

How about this:

>>> s = "hello"
>>> lst = [1, 2, 3, 4, 5]
>>> zip(s, lst)
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]

Note that here it works since the list and string are of equal length. otherwise, you might have truncations.

EDIT:

>>> s = "hell"
>>> lst = [1, 2, 3, 4, 5]
>>> zip(s, lst)
[('h', 1), ('e', 2), ('l', 3), ('l', 4)]

you have the last item in lst missed out.

Upvotes: 7

user2555451
user2555451

Reputation:

This is a snap with zip:

>>> s="hello"
>>> lst=[1,2,3,4,5]
>>> zip(s, lst)
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
>>>

Note that I wrote this in Python 2.x. In Python 3.x, you will need to do this:

>>> s="hello"
>>> lst=[1,2,3,4,5]
>>> zip(s, lst)
<zip object at 0x021C36C0>
>>> list(zip(s, lst))
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]
>>>

This is because, as demonstarted, the Python 3.x zip returns a zip object instead of a list like it did in Python 2.x.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213311

Use zip() function:

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.

Demo:

>>> s="hello"
>>> lst=[1,2,3,4,5]
>>>
>>> zip(s, lst)
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('o', 5)]

Note that, in Python 3.x, zip() returns an iterator. You have to wrap the return value in list(zip(s, lst)), to make it a list.

To get an iterator in Python 2.x, use itertools.izip(). Also, if the length of your sequences are not equal, then you can use itertools.izip_longest().

>>> s="hell"  # len(s) < len(lst)
>>> lst=[1,2,3,4,5]
>>>
>>> zip(s, lst)  # Iterates till the length of smallest sequence
[('h', 1), ('e', 2), ('l', 3), ('l', 4)]
>>>
>>> from itertools import izip_longest
>>> list(izip_longest(s, lst, fillvalue='-'))
[('h', 1), ('e', 2), ('l', 3), ('l', 4), ('-', 5)]

Upvotes: 5

Related Questions