确保Python列表中只存在子列表的单个成员

2024-04-26 02:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个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

Tags: 函数列表成员字符one元组there法律
3条回答

也许是这个?你知道吗

def ensure_at_most_one_number(combo):
    i = len(combo) - 1      # start with the last element
    found_number = False

    while i >= 0:
        try:
            int(combo[i])   # check element is a number
            if  found_number == True:
                del combo[i]    # remove it if a number already found
            else:
                found_number = True
        except ValueError:
            pass             # skip element if not a number
        i -= 1

    return combo

我想不出任何一条线来解决这个问题,但我相信这已经足够简洁了。你知道吗

    def only_one_number(combo):
        import random

        try:
            number = random.choice([x for x in combo if x in legal_numbers])
            combo[:] = [x for x in combo if x in legal_letters]
            combo.append(number)
        except IndexError:
            pass

如果您没有立即看到异常处理的必要性,我们需要捕获由于尝试将空列表传递给随机选择(). 你知道吗

不是最好的,但应该管用

numbers = []
for i in legal_numbers:
  if i in combo:
    numbers.append(i)
    combo.remove(i)
if len(numbers) == 0:
  return combo
combo.append(random.choice(numbers))
return combo

相关问题 更多 >