为了账号安全,请及时绑定邮箱和手机立即绑定

具有嵌套循环和 if 条件的列表理解,以及新列表的成员资格

具有嵌套循环和 if 条件的列表理解,以及新列表的成员资格

GCT1015 2022-06-14 15:20:08
这是我的带有 if 条件的常规嵌套循环,以及新列表的成员资格:wordlist = ["micro", "macro", "stats"]letterlist = []for aword in wordlist:    for aletter in aword:        if aletter not in letterlist:              letterlist.append(aletter)print(letterlist)打印出没有重复的字母:['m', 'i', 'c', 'r', 'o', 'a', 's', 't']当我尝试使用列表理解做同样的事情时,我只能通过嵌套循环:wordlist = ["micro", "macro", "stats"]letterlist = [aletter for aword in wordlist for aletter in aword]print(letterlist)这将打印所有重复的字母:['m', 'i', 'c', 'r', 'o', 'm', 'a', 'c', 'r', 'o', 's', 't', 'a', 't', 's']不幸的是,这不起作用:wordlist = ["micro", "macro", "stats"]letterlist = [[if aletter not in letterlist] for aword in wordlist for aletter in aword]问题:如何根据上面的示例使用列表推导式执行带有 if 语句的嵌套循环?提前致谢
查看完整描述

4 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

您可以使用函数dict.fromkeys()和chain.from_iterable():


from itertools import chain


list(dict.fromkeys(chain.from_iterable(wordlist)))

# ['m', 'i', 'c', 'r', 'o', 'a', 's', 't']

在 Python 3.6 及更低版本中,您需要替换dict为OrderedDict.


查看完整回答
反对 回复 2022-06-14
?
慕姐8265434

TA贡献1813条经验 获得超2个赞

不可以。你不能使用列表推导来做到这一点,因为你需要创建一个已经看到的字母列表。我相信您最好的做法是使用 for 循环。如果您需要保持字母的顺序,请同时使用列表和集合(保持顺序的列表,集合对每个字母进行 O(1) 成员资格测试)。如果顺序无关紧要,那么只需使用集合理解,即{letter for word in word_list for letter in word}


请注意,使用列表推导来解决其副作用(即创建已看到的字母的辅助列表)并不是 Pythonic。 将列表推导用于副作用是 Pythonic 吗?


word_list = ["micro", "macro", "stats"]

letter_list = []

letters_seen = set()


for word in word_list:

    for letter in word:

        if letter in letters_seen:

            continue

        letters_seen.add(letter)

        letter_list.append(letter)


>>> letter_list

['m', 'i', 'c', 'r', 'o', 'a', 's', 't']

时间


wordlist = ["micro", "macro", "stats"] * 100_000


%%timeit

res=[]

[res.append(aletter) for aword in wordlist for aletter in aword if aletter not in res]

# 174 ms ± 8.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


%%timeit

letter_list = []

letters_seen = set()


for word in wordlist:

    for letter in word:

        if letter in letters_seen:

            continue

        letters_seen.add(letter)

        letter_list.append(letter)

# 71.1 ms ± 1.15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


%timeit list(dict.fromkeys(''.join(wordlist)))

# 37.1 ms ± 1.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


%timeit list(dict.fromkeys(chain.from_iterable(wordlist)))

# 46.8 ms ± 2.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Slightly slower, but requires less memory to run.


# Baseline comparison if order is not important (i.e. use sets).

%timeit {letter for word in wordlist for letter in word}

# 88.8 ms ± 6.48 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


查看完整回答
反对 回复 2022-06-14
?
湖上湖

TA贡献2003条经验 获得超2个赞

您可以通过以下方式执行此操作


from collections import OrderedDict


wordlist = ["micro", "macro", "stats"]    

sol = list(OrderedDict.fromkeys(''.join(wordlist)).keys())    

print(sol)

输出


['m', 'i', 'c', 'r', 'o', 'a', 's', 't']

你也可以使用


sol =  [*OrderedDict.fromkeys(''.join(wordlist)).keys()]

使用dict它可以做为


  sol = list(dict((i,1) for i in ''.join(wordlist)).keys())

在此处添加@alexander 解决方案


sol = list(dict.fromkeys(''.join(wordlist)))    


查看完整回答
反对 回复 2022-06-14
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

您可以将输出保存在单独的列表中,例如:


wordlist = ["micro", "macro", "stats"]

res=[]

[res.append(aletter) for aword in wordlist for aletter in aword if aletter not in res]

print(res)

或者


list(set([aletter for aword in wordlist for aletter in aword]))

希望这可以帮助!


查看完整回答
反对 回复 2022-06-14
  • 4 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号