开发者

Some ways to combine sets in python

I am trying to write a game that uses grids, and I need a way to make s开发者_Python百科ets by combining two other sets.

For example, if I had [a, b, c] and [1, 2, 3], are there are any functions in Python 3 that will give me [a1, a2, a3, b1, b2, b3, c1, c2, c3]?


Use itertools.product:

In [41]: import itertools

In [42]: x='abc'

In [43]: y='123'

In [45]: [letter+num for letter,num in itertools.product(x,y)]
Out[45]: ['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']


http://docs.python.org/tutorial/datastructures.html

Take a look at the map function.


letters = ["a", "b", "c"]
numbers = [ 1 ,  2 ,  3 ]

[x + str(y) for x in letters for y in numbers]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜