相关疑难解决方法(0)

python:将"5,4,2,4,1,0"转换为[[5,4],[2,4],[1,0]]

是否有一种"简单"的方法将包含数字的str转换为[x,y]整数列表?

# from: '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
# to: [[5, 4], [2, 4], [1, 0], [3, 0], [5, 1], [3, 3], [14, 32], [3, 5]]
Run Code Online (Sandbox Code Playgroud)

顺便说一句,下面的工作,但不会直接称之为...此外,可以假设输入str已经过验证,以确保它只包含偶数个逗号交错的数字.

num_str = '5,4,2,4,1,0,3,0,5,1,3,3,14,32,3,5'
numpairs_lst = []      # ends up as [[5, 4], [2, 4], [1, 0], ...]

current_num_str = ''   # the current num within the str; stop when a comma is found
xy_pair = []           # this is one of the [x,y] pairs -> [5, 4] 
for ix,c in enumerate(num_str):
    if c == ',':
        xy_pair.append(int(current_num_str))
        current_num_str …
Run Code Online (Sandbox Code Playgroud)

python

9
推荐指数
3
解决办法
2756
查看次数

Python:使用生成器的给定集合的powerset

我正在尝试使用生成器在Python中构建给定集的子集列表.说我有

set([1, 2, 3])

作为输入,我应该

[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]

作为输出.我怎样才能做到这一点?

python algorithm generator set powerset

6
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×2

algorithm ×1

generator ×1

powerset ×1

set ×1