我有几个N维数组,如下所示。如何将这些数组转换为元组?
num = ['1' '2']
letter1 = ['a' 'b' 'c' 'd' 'e' 'f']
letter2 = ['aa' 'bb' 'cc' 'dd' 'ee' 'ff']
我想要的结果是:
tuple1 = [(1,a),(1,b),(1,c),(1,d),(1,e),(1,f)]
tuple2 = [(2,aa),(2,bb),(2,cc),(2,dd),(2,ee),(2,ff)]
我有
tuple1 = tuple(num[0], letter1)
tuple2 = tuple(num[1], letter2)
但我收到了TypeError: tuple() takes at most 1 argument (2 given)
你的方法是什么?任何方法将不胜感激。感谢。
答案 0 :(得分:6)
您可以zip
使用itertools.repeat
来实现此目的:
>>> from itertools import repeat
>>> num = ['1', '2']
>>> letter1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> tuple1 = list(zip(repeat(num[0]), letter1))
>>> tuple1
[('1', 'a'), ('1', 'b'), ('1', 'c'), ('1', 'd'), ('1', 'e'), ('1', 'f')]
PS: 请注意上述列表中元素之间的逗号,
。不使用逗号分隔的字符串将被视为单个字符串。
从上面的答案中得到启发,这里是列表理解版本的解决方案,只需一次获取tuple1
和tuple2
:
letter2 = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] # rest of the variables same as the above solution
tuple1, tuple2 = [list(zip(repeat(a), b)) for a, b in zip(num, (letter1, letter2))]
这些变量将以下列表保存为值:
>>> tuple1
[('1', 'a'), ('1', 'b'), ('1', 'c'), ('1', 'd'), ('1', 'e'), ('1', 'f')]
>>> tuple2
[('2', 'aa'), ('2', 'bb'), ('2', 'cc'), ('2', 'dd'), ('2', 'ee'), ('2', 'ff')]
答案 1 :(得分:2)
您可以使用iter
和next
:
num = ['1', '2']
num = iter(num)
letter1 = ['a', 'b', 'c', 'd', 'e', 'f']
letter2 = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
tuple1, tuple2 = [list(zip(i, [next(num)]*len(i))) for i in [letter1, letter2]]
输出:
[('a', '1'), ('b', '1'), ('c', '1'), ('d', '1'), ('e', '1'), ('f', '1')]
[('aa', '2'), ('bb', '2'), ('cc', '2'), ('dd', '2'), ('ee', '2'), ('ff', '2')]
没有iter
:
tuple1, tuple2 = [[(i, h) for i in c] for c, h in zip([letter1, letter2], ['1', '2'])]
答案 2 :(得分:1)
已经有一些好的答案,但我将使用列表理解来分享另一种选择。它看起来像更多的代码,但适用于更长的nums
和lists
(只要它们的长度仍然相同):
letter1 = ['a', 'b', 'c', 'd', 'e', 'f']
letter2 = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
nums = [1, 2]
lists = [letter1, letter2]
tuples = [[(i, x) for x in l] for i, l in zip(nums, lists)]
tuple1, tuple2 = tuples
结果:
In [1]: tuple1
Out[1]: [(1, 'a'), (1, 'b'), (1, 'c'), (1, 'd'), (1, 'e'), (1, 'f')]
In [2]: tuple2
Out[2]: [(2, 'aa'), (2, 'bb'), (2, 'cc'), (2, 'dd'), (2, 'ee'), (2, 'ff')]
答案 3 :(得分:1)
已经有很好的答案了,我只想给你提示你可以稍微调整一下你的逻辑
num = ['1','2']
letter1 = ['a','b' ,'c', 'd', 'e', 'f']
letter2 = ['aa' ,'bb', 'cc', 'dd' ,'ee' ,'ff']
tuple1 = tuple(zip(*[[int(num[0])]*len(letter1),letter1]))
tuple2 = tuple(zip(*[[int(num[1])]*len(letter2), letter2]))
print(tuple1)
print(tuple2)
输出:
((1, 'a'), (1, 'b'), (1, 'c'), (1, 'd'), (1, 'e'), (1, 'f'))
((2, 'aa'), (2, 'bb'), (2, 'cc'), (2, 'dd'), (2, 'ee'), (2, 'ff'))