创建一个列表t,如果其中包含“t”,则只保存运动员的姓名。如果不包含字母“t”,则将运动员姓名保存到列表oth中

2024-05-14 14:36:50 发布

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

athletes = [['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], ['Felix', 'Bolt', 'Gardner', 'Eaton'], ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton']]

t = [] 
other = []

for lst in athletes:
    for lst2 in athletes:
        if 't' in lst2:
            t.append(lst2)
        else:
            other.append(lst2)

Tags: inforotherboltappendathletesfelixfranklin
3条回答

Try it online!

for x in [item for sublist in athletes for item in sublist]:
    t.append(x) if 't' in x else other.append(x)

输出:

t:  ['Lochte', 'Bolt', 'Eaton', 'Dalton']
other:  ['Phelps', 'Schooling', 'Ledecky', 'Franklin', 'Felix', 'Gardner', 'Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak']
# make a "flat" list of names
flat_list = sum(athletes, [])


# use list comprehensions
t = [x for x in flat_list if "t" in x]
other = [x for x in flat_list if "t" not in x]

我们可以使用来自^{}partition配方。你知道吗

from itertools import chain, tee, filterfalse

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10))  > 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

athletes = [['Phelps', 'Lochte', 'Schooling', 'Ledecky', 'Franklin'], ['Felix', 'Bolt', 'Gardner', 'Eaton'], ['Biles', 'Douglas', 'Hamm', 'Raisman', 'Mikulak', 'Dalton']]
flat_athletes = chain.from_iterable(athletes)

without_t, with_t = partition(lambda ath: "t" in ath, flat_athletes)

without_twith_t与be迭代器。如果你想把它们列出来,只需做without_t = list(witout_t)。你知道吗

相关问题 更多 >

    热门问题