假设我有一个Python列表,其中可能包含来自以下两个元组的成员的任意组合:
legal_letters = ('a', 'b', 'c')
legal_numbers = (1, 2, 3)
所以法律上的合并清单应该包括
combo1 = ['a', 1, '3']
combo2 = ['c']
combo3 = ['b', 2, 1, 'c']
任何长度,任何组合。不过,您可以假设组合列表中不会有重复的字符。我想对这些组合应用一个函数,对它们进行适当的修改,使它们最多包含一个元组的一个成员——比如说数字。数字元组的“selected”成员应随机选择。我也不在乎在这个过程中订单是否被破坏。你知道吗
def ensure_at_most_one_number(combo):
# My first attempts involved set math and a while loop that was
# pretty gross, I'll spare you guys the details. I'm sure I could get it to work
# but I figured there might be a one-liner or some fancy itertools out there
return combo
# Post transformation
combo1 = ['a', '1']
combo2 = ['c']
combo3 = ['c', 'b', 2] # Mangled order, not a problem
也许是这个?你知道吗
我想不出任何一条线来解决这个问题,但我相信这已经足够简洁了。你知道吗
如果您没有立即看到异常处理的必要性,我们需要捕获由于尝试将空列表传递给随机选择(). 你知道吗
不是最好的,但应该管用
相关问题 更多 >
编程相关推荐