python中怎么把值添加进列表_Python:如何将生成器迭代值附加到列表中

I have a simple generator to give me permutations of a set of coordinates.

I wish to save each new permutation to an element in an array using the code below:

import random

def poss_comb(coord):

spin=random.shuffle

if spin:

spin(coord)

yield (coord)

...

a=[]

for n in xrange(0,10):

for item in poss_comb(coord):

print item

a.append(item)

However when printing the results printing item gives me what I want :

['0 1', '', '1 2', '1 3']

['0 1', '', '1 2', '1 3']

['1 2', '0 1', '1 3', '']

['0 1', '1 2', '', '1 3']

['1 3', '', '1 2', '0 1']

['1 3', '1 2', '0 1', '']

['0 1', '', '1 3', '1 2']

['1 2', '0 1', '', '1 3']

['1 2', '1 3', '', '0 1']

['', '1 2', '1 3', '0 1']

whereas printing list a provides an array where each element is a copy of the last permutation.

What would be a better way to do this?

解决方案

Your generator does not yield new lists, it yields the same list over and over again. When you append that yielded reference to a you only get to see the same original list, in it's most recently shuffled form, over and over again.

Yield a copy instead:

def poss_comb(coord):

coord = coord[:] # use a local copy of the list

random.shuffle(coord)

yield coord

or create a random sort instead of using inplace shuffling with the sorted() function:

def poss_comb(coord):

yield sorted(coord, key=lambda k: random.random())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值