简体   繁体   English

如果元素包含在列表中,则从列表中删除元组

[英]remove tuple from list if element is contained within it

I have a list of players and a list of tuples我有一个玩家列表和一个元组列表

players = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
shortlist = [('a', 'b'), ('c', 'd'), ('e',)]

There are two pairs and a single tuple.有两对和一个元组。 I want each player to choose one tuple from the shortlist, however they cannot choose the tuple which they are in, if they are in the shortlist.我希望每个玩家从候选名单中选择一个元组,但是如果他们在候选名单中,他们就不能选择他们所在的元组。

My current attempt:我目前的尝试:

for person in players:
    for item in shortlist:
        if person in item:
            new_list = shortlist.remove(item)
            their_choice = random.choices(new_list, k=1)
            df[person] = their_choice

But I am just getting empty values in the dataframe.但我只是在数据框中得到空值。 I think there must be a way to do this using list comprehension but I can't quite figure it out.我认为必须有一种方法可以使用列表理解来做到这一点,但我无法弄清楚。 Thanks in advance提前致谢

You wouldn't want to modify the list whilst looping over it (eg with remove ).您不想在循环时修改列表(例如使用remove )。

Perhaps you're looking for something like this?也许你正在寻找这样的东西?

import random
choices = []
for person in players:
    eligible_items = [item for item in shortlist if person not in item]
    their_choice = random.choices(eligible_items)[0]
    choices.append(their_choice)

Or in one big list comprehension?或者在一个大列表理解中?

[
    random.choices([item for item in shortlist if person not in item])[0]
    for person in players
]

modifying your code a little the second loop can be done in a list comprehension, so something like this should work:稍微修改你的代码,第二个循环可以在列表理解中完成,所以这样的事情应该可以工作:

for person in players:
    df[person] = random.choices(shortlist, [person not in choice for choice in shortlist])

what is happening here is we assign a weight to each choice in the second argument of choices.这里发生的事情是我们在选择的第二个参数中为每个选择分配一个权重。 The weights are calculated using list comprehension for every person and they are False for the choice containing the person and True for the others.权重是使用列表理解计算每个人的,对于包含该人的选择,它们是False ,对于其他人,它们是True Luckily random.choices() accepts True False list as weights or conversion to 0 and 1 would be needed.幸运的是random.choices()接受 True False 列表,因为需要权重或转换为 0 和 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM