简体   繁体   中英

Python: list manipulation from return function

In my code I'm trying to divide all of the second row in the nested list by the variable. This works fine but it asks for the variable for every item on the list instead of just once.

This is the code I have:

nlist = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]

def divide():
    x = int(input('what is your divider?:'))
    return x

nlist[1] = [num / divide() for num in nlist[1]]
print(nlist)

Output:

what is your divider?:5
what is your divider?:5
what is your divider?:5
what is your divider?:5
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]]

What I want the output to be:

what is your divider?:5
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]]
nlist[1] = [num / divide() for num in nlist[1]]

divide() is called each time. Use

divide_value = divide()
nlist[1] = [num / divide_value for num in nlist[1]]

to call it once only and store it.

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