比方說,我有可能包含來自以下兩元組成員的任意組合Python列表:確保子表的只有一個成員存在於Python列表
legal_letters = ('a', 'b', 'c')
legal_numbers = (1, 2, 3)
所以合法組合名單將包括
combo1 = ['a', 1, '3']
combo2 = ['c']
combo3 = ['b', 2, 1, 'c']
任何長度,任意組合。儘管如此,您可以假定沒有重複的字符會出現在組合列表中。我想對那些修改它們的組合(就地)應用一個函數,使得它們包含至多一個元組中的單個成員 - 比如它是數字。數字元組的「選定」成員應該隨機選擇。我也不在乎訂單在整個過程中是否受到損壞。
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