2

接下来是(工作)尝试组合元组,使得第 i 个元组的第 i 个成员取自第二个元组,其余成员取自第一个元组。

just_no =  ('Gruyere', 'Danish Blue', 'Cheshire')
missing =  ('Caerphilly', 'Red Windsor', 'Camembert')
shop_window = tuple(tuple(no if i!=j else gone 
                          for i, no in enumerate(just_no)) 
                    for j, gone in enumerate(missing))
print(shop_window, "\nWhat a senseless waste of human life.") 
# (('Caerphilly', 'Danish Blue', 'Cheshire'), ('Gruyere', 'Red Windsor', 'Cheshire'), ('Gruyere', 'Danish Blue', 'Camembert'))
# What a senseless waste of human life.

它很有效,我想知道是否有更优雅的解决方案,可能使用 itertools?

4

3 回答 3

2

基于 Python索引/切片的单线:

just_no =  ('Gruyere', 'Danish Blue', 'Cheshire')
missing =  ('Caerphilly', 'Red Windsor', 'Camembert')
shop_window = tuple(just_no[:i] + (gone,) + just_no[i+1:] for i, gone in enumerate(missing))
print(shop_window)

输出:

(('Caerphilly', 'Danish Blue', 'Cheshire'), ('Gruyere', 'Red Windsor', 'Cheshire'), ('Gruyere', 'Danish Blue', 'Camembert'))
于 2019-09-15T10:19:09.737 回答
1

您可以使用元组的解包功能并编写以下内容:

just_no =  ('Gruyere', 'Danish Blue', 'Cheshire')
missing =  ('Caerphilly', 'Red Windsor', 'Camembert')
shop_window = tuple((*just_no[0:i], missing[i], *just_no[i+1:]) for i in range(0, len(just_no)))
于 2019-09-15T10:14:36.810 回答
0

您也可以使用zip

just_no =  ('Gruyere', 'Danish Blue', 'Cheshire')
missing =  ('Caerphilly', 'Red Windsor', 'Camembert')
shop_window = tuple((tuple(map(lambda x : x[1][1] if x[0] == i else x[1][0], enumerate(zip(just_no, missing)))) for i in range(0, len(just_no))))
于 2019-09-15T10:47:08.207 回答