Python 3 教程 在线

1088Python3 编程第一步

print() sep 参数使用:

>>> a=10;b=388;c=98
>>> print(a,b,c,sep='@')
10@388@98

1087Python3 集合

集合用 set.pop() 方法删除元素的不一样的感想如下:

1、对于 python 中列表 list、tuple 类型中的元素,转换集合是,会去掉重复的元素如下:

>>> list = [1,1,2,3,4,5,3,1,4,6,5]
>>> set(list)
{1, 2, 3, 4, 5, 6}
>>> tuple = (2,3,5,6,3,5,2,5)
>>> set(tuple)
{2, 3, 5, 6}

2、集合对 list 和 tuple 具有排序(升序),举例如下:

>>> set([9,4,5,2,6,7,1,8])
{1, 2, 4, 5, 6, 7, 8, 9}
>>> set([9,4,5,2,6,7,1,8])
{1, 2, 4, 5, 6, 7, 8, 9}

3、集合的 set.pop() 的不同认为

有人认为 set.pop() 是随机删除集合中的一个元素、我在这里说句非也!对于是字典和字符转换的集合是随机删除元素的。当集合是由列表和元组组成时、set.pop() 是从左边删除元素的如下:

列表实例:

set1 = set([9,4,5,2,6,7,1,8])
print(set1)
print(set1.pop())
print(set1)

输出结果:

{1, 2, 4, 5, 6, 7, 8, 9}
1
{2, 4, 5, 6, 7, 8, 9}

元组实例:

set1 = set((6,3,1,7,2,9,8,0))
print(set1)
print(set1.pop())
print(set1)

输出结果:

{0, 1, 2, 3, 6, 7, 8, 9}
0
{1, 2, 3, 6, 7, 8, 9}
 

1086Python3 集合

set() 中参数注意事项

1.创建一个含有一个元素的集合

>>> my_set = set(('apple',))
>>> my_set
{'apple'}

2.创建一个含有多个元素的集合

>>> my_set = set(('apple','pear','banana'))
>>> my_set
{'apple', 'banana', 'pear'}

3.如无必要,不要写成如下形式

>>> my_set = set('apple')
>>> my_set
{'l', 'e', 'p', 'a'}
>>> my_set1 = set(('apple'))
>>> my_set1
{'l', 'e', 'p', 'a'}

1085Python3 集合

s.update( "字符串" ) 与 s.update( {"字符串"} ) 含义不同:

  • s.update( {"字符串"} ) 将字符串添加到集合中,有重复的会忽略。
  • s.update( "字符串" ) 将字符串拆分单个字符后,然后再一个个添加到集合中,有重复的会忽略。
>>> thisset = set(("Google", "facesho", "Taobao"))
>>> print(thisset)
{'Google', 'facesho', 'Taobao'}
>>> thisset.update({"Facebook"})
>>> print(thisset) 
{'Google', 'facesho', 'Taobao', 'Facebook'}
>>> thisset.update("Yahoo")
>>> print(thisset)
{'h', 'o', 'Facebook', 'Google', 'Y', 'facesho', 'Taobao', 'a'}
>>>

1084Python3 字典

字典列表,即在列表中嵌套字典:

dict_0 = {'color': 'green', 'points': 5} 
dict_1 = {'color': 'yellow', 'points': 10} 
dict_2 = {'color': 'red', 'points': 15}
lists = [dict_0, dict_1, dict_2]
for dict in lists: 
    print(dict)

输出:

{'color': 'green', 'points': 5} 
{'color': 'yellow', 'points': 10} 
{'color': 'red', 'points': 15}