列表理解与集合理解

liv*_*hak 7 python

我有以下程序.我正在尝试理解列表理解和设置理解

mylist = [i for i in range(1,10)]
print(mylist)

clist = []

for i in mylist:
    if i % 2 == 0:
        clist.append(i)


clist2 = [x for x in mylist if (x%2 == 0)]

print('clist {} clist2 {}'.format(clist,clist2))

#set comprehension
word_list = ['apple','banana','mango','cucumber','doll']
myset = set()
for word in word_list:
    myset.add(word[0])

myset2 = {word[0] for word in word_list}

print('myset {} myset2 {}'.format(myset,myset2))
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么花括号为myset2 = {字[0]在WORD_LIST词}.我还没有碰到来设定中的细节.

Syn*_*cus 11

曲线括号用于字典和集合理解.创建哪一个取决于您是否提供相关值,如下面的(3.4):

>>> a={x for x in range(3)}
>>> a
{0, 1, 2}
>>> type(a)
<class 'set'>
>>> a={x: x for x in range(3)}
>>> a
{0: 0, 1: 1, 2: 2}
>>> type(a)
<class 'dict'>
Run Code Online (Sandbox Code Playgroud)


Net*_*ave 7

Set是一个无序、可变的不重复元素集合。

在 python 中,你可以set()用来构建一个集合,例如:

set>>> set([1,1,2,3,3])
set([1, 2, 3])
>>> set([3,3,2,5,5])
set([2, 3, 5])
Run Code Online (Sandbox Code Playgroud)

或者使用集合推导式,如列表推导式,但带有花括号:

>>> {x for x in [1,1,5,5,3,3]}
set([1, 3, 5])
Run Code Online (Sandbox Code Playgroud)

  • @oldwooki,实际上,你是对的。我不知道为什么,但我用字典[它们有插入顺序]错误或推断了这一点(/sf/ask/2798622641/)让我恢复这个。并感谢您的指出! (3认同)