如何合并元组列表中各元组元素并转换为指定嵌套列表格式?
Solution
Sure thing! Here are two straightforward ways to achieve your desired output:
Convert Existing List A
If you already have the list of tuples A and just need to transform it, you can use a list comprehension to process each tuple:
A = [(1, 2, 3), (3, 4, 5), (3, 5, 7)] result = [[int(''.join(map(str, t)))] for t in A] print(result) # Output: [[123], [345], [357]]
How this works:
map(str, t)converts each integer in the tupletto a string (e.g.,(1,2,3)becomes['1','2','3']).''.join(...)concatenates those strings into a single string (e.g.,'123').int(...)converts the concatenated string back to an integer (e.g.,123).- Wrapping the result in
[]turns it into a single-element list, and the outer list comprehension applies this to every tuple inA.
Modify Your Converter Function
To get the desired output directly from your permutation-generating function, you can modify the return statement to process each permutation tuple before returning it. Don't forget to import itertools if you haven't already:
import itertools def converter(N): y = list(str(N)) t = [int(x) for x in y] permutations = list(itertools.permutations(t)) # Process each permutation into the desired format return [[int(''.join(map(str, perm)))] for perm in permutations] r = converter(345) print(r) # Output: [[345], [354], [435], [453], [534], [543]]
This way, the function returns the permutations already formatted as single-element lists containing the concatenated integer, instead of tuples of individual digits.
内容的提问来源于stack exchange,提问作者camarman
相关产品推荐
相关产品推荐

