简体   繁体   中英

Pythonic way to generate a list of possible arrays

Given an array of numbers (eg [3, 5, 2]), I'm trying to generate a list of possible arrays that result from adding 1 to one entry in the array: [[4, 5, 2], [3, 6, 2], [3, 5, 3]].

I can get it done by the following, but wondering if there's a more pythonic way to get the result?

test = [3, 5, 2]
result = [t.copy() for _ in range(len(test))]
for index, _ in enumerate(result):
    result[index][index] += 1

Here's how to do it with a list comprehension:

test = [3, 5, 2]   
print [test[:i] + [v + 1] + test[i+1:] for i,v in enumerate(test)]

output

[[4, 5, 2], [3, 6, 2], [3, 5, 3]]

Here is another inline solution with list comprehension:

test = [3, 5, 2]
result = [[v+1 if i==j else v for j, v in enumerate(test)] for i in range(len(test))]

or, as noticed by PM 2Ring , you can exploit the fact that True == 1 and False == 0 :

result = [[v + (i==j) for j, v in enumerate(test)] for i in range(len(test))]

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