简体   繁体   中英

How to neatly pass each item of a Python list to a function and update the list (or create a new one)

Given a list of floats spendList , I want to apply round() to each item, and either update the list in place with the rounded values, or create a new list.

I'm imagining this employing list comprehension to create the new list (if the original can't be overwritten), but what about the passing of each item to the round() ?

I discovered sequence unpacking here so tried:

round(*spendList,2)

and got:

TypeError                                 Traceback (most recent call last)
<ipython-input-289-503a7651d08c> in <module>()
----> 1 round(*spendList)

TypeError: round() takes at most 2 arguments (56 given)

So surmising that round was trying to round each item in the list, I tried:

[i for i in round(*spendList[i],2)]

and got:

In [293]: [i for i in round(*spendList[i],2)]
  File "<ipython-input-293-956fc86bcec0>", line 1
    [i for i in round(*spendList[i],2)]
SyntaxError: only named arguments may follow *expression

Can sequence unpacking even be used here? If not, how can this be achieved?

You have your list comprehension the wrong way around:

[i for i in round(*spendList[i],2)]

should be:

[round(i, 2) for i in spendList]

You want to iterate over spendList , and apply round to each item in it. There's no need for * ( "splat" ) unpacking here; that's generally only needed for functions that take an arbitrary number of positional arguments (and, per the error message, round only takes two).

You can use map() function for this -

>>> lst = [1.43223, 1.232 , 5.4343, 4.3233]
>>> lst1 = map(lambda x: round(x,2) , lst)
>>> lst1
[1.43, 1.23, 5.43, 4.32]

For Python 3.x , you need to use list(map(...)) as in Python 3.x map returns an iterator not a list.

you could still use the list comprehension you talked aobut, just this way:

list = [1.1234, 4.556567645, 6.756756756, 8.45345345]
new_list = [round(i, 2) for i in list]

new_list will be: [1.12, 4.56, 6.76, 8.45]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM