我有以下程序.我正在尝试理解列表理解和设置理解
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 = {字[0]在WORD_LIST词}.我还没有碰到来设定中的细节.
曲线括号用于字典和集合理解.创建哪一个取决于您是否提供相关值,如下面的(3.4):
>>> a={x for x in range(3)} >>> a {0, 1, 2} >>> type(a)>>> a={x: x for x in range(3)} >>> a {0: 0, 1: 1, 2: 2} >>> type(a)