[英]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]]. 给定一个数组(例如[3,5,2]),我试图生成一个可能的数组列表,这些数组是在数组中添加1到1个条目得到的:[[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? 我可以通过以下方式完成它,但想知道是否有更多的pythonic方式来获得结果?
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
: 或者,正如PM 2Ring所注意到的,你可以利用
True == 1
和False == 0
的事实:
result = [[v + (i==j) for j, v in enumerate(test)] for i in range(len(test))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.