列表理解与集合理解

2024-05-20 00:38:05 发布

您现在位置: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))

我的问题是,为什么myset2的大括号是{word[0],word中的大括号是{/strong>,我以前没有遇到过详细的集合。


Tags: in程序formatforif大括号listword
2条回答

大括号用于字典和集合理解。创建哪一个取决于是否提供关联值,如下(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'>

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

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

set>>> set([1,1,2,3,3])
set([1, 2, 3])
>>> set([3,3,2,5,5])
set([2, 3, 5])

或者使用集合理解,如列表理解,但使用大括号:

>>> {x for x in [1,1,5,5,3,3]}
set([1, 3, 5])

相关问题 更多 >