简体   繁体   中英

Python list of lists to divide an element position on all sublists by a number

How can in python take a lists of lists and apply a division to the third element of each sublist.

The sublists looks like this

[1.3735876284e-05, 0.9277849431216683, 34.02875434027778, 0.0]
[2.60440773e-06,   7.35174234e-01,   2.79259180e+02,   0.00000000e+00]
...

I need to get the same sublists but the third element of each sublist (34.02 ..., 2.79 ...) should be divided by 100

使用列表理解来提取子列表,并使用加法连接列表部分...

lambda L: [l[:2]+[l[2]/100]+l[3:] for l in L]

You could try this:

a = [
    [1.3735876284e-05, 0.9277849431216683, 34.02875434027778, 0.0],
    [2.60440773e-06,   7.35174234e-01,   2.79259180e+02,   0.00000000e+00],
]
b = [
    [(x / 100.0 if i == 2 else x) for (i, x) in enumerate(lst)] 
        for lst in a
]

Or the lambda version:

f = lambda a: [
    [(x / 100.0 if i == 2 else x) for (i, x) in enumerate(lst)] 
        for lst in a
]
b = f(a)

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