I have a list as
alist = [[], [(u'0.77',)], [(u'0.34',)], [(u'0.12',)], [(u'0',)], [(u'0.0',)], [(u'0',)]]

I'm trying to get it as like this
[0.77, 0.34, 0.12, 0, 0.0, 0] using the statement
rlist= map(lambda a: int(a), alist) but got an error as,
TypeError: int() argument must be a string or a number, not 'list'
I could be missing a basic concept to get it done but not sure how, please do help.

Recommended Answers

All 8 Replies

a[0], the first value, but you get trouble with first empty list. It is more flexible to use list comprehension instead of map.

Just more complex since you also have tuples in your list. This may work:

alist = [[], [(u'0.77',)], [(u'0.34',)], [(u'0.12',)], [(u'0',)], [(u'0.0',)], [(u'0',)]]

value_list = [float(x[0][0]) for x in alist if x]


[0.77, 0.34, 0.12, 0.0, 0.0, 0.0]

Or like this.

>>> [float(numb[0]) for item in alist for numb in item]
[0.77, 0.34, 0.12, 0.0, 0.0, 0.0]   

If i break up list comprehension up it can be eaiser du understand what`s going on.

>>> alist = [[], [(u'0.77',)], [(u'0.34',)], [(u'0.12',)], [(u'0',)], [(u'0.0',)], [(u'0',)]]
>>> numb_list = []
>>> for item in alist:
        for numb in item:

>>> numb_list
[0.77, 0.34, 0.12, 0.0, 0.0, 0.0]

Thank you all :)

this time my list is with negative integers, alist = [[u'', u'-0', u'-3', u'-6', u'-9', u'-12', u'-15', u'-18']]
when I do [int(x[0])for x in xval if x]
I get an error as [int(x[0])for x in xval if x]
ValueError: invalid literal for int() with base 10: '-'
please do suggest a good book to learn these tips/tricks or does it comes by experience. Thank you.

what that -0 means ;-)

@MS, its a typo but it has no effect on the result though

You basic problem is explained here ...

alist = [[u'', u'-0', u'-3', u'-6', u'-9', u'-12', u'-15', u'-18']]

# alist is a list within a list, so use alist[0]
# the if x statement filters out the empty string u''
xval  = [int(x) for x in alist[0] if x]

print(xval)  # test

[0, -3, -6, -9, -12, -15, -18]

You can find a good elementary book on Python here:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.