想象一下我有一个元组,其中包含一个列表。
例如:
t = (1, 2, 3, 4 [5, 6, 7])
好吧,我想把它们保存在元组和列表中的所有数字。我怎么做?在另外我知道如何获取它们在元组中保存的数字。我只需解压缩元组并获取所有数字,保存在lis中,我会迭代它。但在这种情况下,我不知道自己该做什么。
有什么想法吗?
了解详情
def work_with_tuple(my_tuple = None):
count_items = len(my_tuple)
if count_items == 2:
first_item, second_item = my_tuple
print "first_item", first_item
print "second_item", second_item
if count_items == 3:
first_item, second_item, third_item = my_tuple
print "first_item", first_item
print "second_item", second_item
# But I have to know, that 'third_item' is a list.
# Should I check every unpacked item if it is a list?
# I think my idea it doesn't sound elegance.
one, two = third_item
print "one", one
print "two", two
print "run first"
print "---------"
# I call the function with easy tuple
work_with_tuple(my_tuple = (2, 3))
# output: first_item 2
# second_item 3
print ""
print "run second"
print "----------"
# I call the function with nested tuple
work_with_tuple(my_tuple = (2, 3, [4, 6]))
# output: first_item 2
# second_item 3
# one 4
# two 6
答案 0 :(得分:0)
您可以迭代元组并检查每个项目。
def unpack(t):
numbers = []
for item in t:
if isinstance(item, list):
numbers += item # add each item of the list into accumulator
else:
numbers.append(item)
return numbers
如果您需要更通用的内容,请参阅this answer。
答案 1 :(得分:0)
通过这种方式访问元组中的列表。
tl = (1,2,3,4,[5,6,7])
print tl
for i in tl:
if isinstance(i, list):
print i[2]
else:
print i
希望您的问题正在使用我的代码解决。