是否有一种"简单"的方法将包含数字的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中构建给定集的子集列表.说我有
set([1, 2, 3])
作为输入,我应该
[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]
作为输出.我怎样才能做到这一点?