Python:集合與字符串格式化


1. 集合

  定義:集合是由不同元素組合而成,集合中是一組無序排列的可hash值,可做為字典的key。

  特征:集合的目的是將不同的值放在一起,不同的集合可以用來做關系運算。集合中的元素必須是不可變類型。可以幫助簡單的去重。

1.1集合的創建

>>> {1,2,3,1}
{1, 2, 3}

或者

>>> set_test = set("hello")
>>> set_test
{'o', 'h', 'l', 'e'}

集合中的元素是不會重復的

frozenset()函數將集合改變為不可變集合

>>> f_set_test=frozenset(set_test)
>>> f_set_test
frozenset({'o', 'h', 'l', 'e'})

1.2集合的函數

 

  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5 
  6     Build an unordered collection of unique elements.
  7     """
  8     def add(self, *args, **kwargs): # real signature unknown
  9         """增加元素,傳一個參數"""
 10         """
 11         Add an element to a set.
 12 
 13         This has no effect if the element is already present.
 14         """
 15         pass
 16 
 17     def clear(self, *args, **kwargs): # real signature unknown
 18         """清除集合內的所有元素"""
 19         """ Remove all elements from this set. """
 20         pass
 21 
 22     def copy(self, *args, **kwargs): # real signature unknown
 23         """淺拷貝集合內的元素"""
 24         """ Return a shallow copy of a set. """
 25         pass
 26 
 27     def difference(self, *args, **kwargs): # real signature unknown
 28         """求差集 相當於集合return a-b"""
 29         """
 30         Return the difference of two or more sets as a new set.
 31 
 32         (i.e. all elements that are in this set but not the others.)
 33         """
 34         pass
 35 
 36     def difference_update(self, *args, **kwargs): # real signature unknown
 37         """a.difference_update(b) 相當於 a = a - b"""
 38         """ Remove all elements of another set from this set. """
 39         pass
 40 
 41     def discard(self, *args, **kwargs): # real signature unknown
 42         """刪除一個元素,元素不存在時不會報錯"""
 43         """
 44         Remove an element from a set if it is a member.
 45 
 46         If the element is not a member, do nothing.
 47         """
 48         pass
 49 
 50     def intersection(self, *args, **kwargs): # real signature unknown
 51         """求兩個集合的交集;相當於 return a & b"""
 52         """
 53         Return the intersection of two sets as a new set.
 54 
 55         (i.e. all elements that are in both sets.)
 56         """
 57         pass
 58 
 59     def intersection_update(self, *args, **kwargs): # real signature unknown
 60         """求兩個集合的交集 更新;相當於 a = a & b"""
 61         """ Update a set with the intersection of itself and another. """
 62         pass
 63 
 64     def isdisjoint(self, *args, **kwargs): # real signature unknown
 65         """如果兩個集合的交集為空,返回true"""
 66         """ Return True if two sets have a null intersection. """
 67         pass
 68 
 69     def issubset(self, *args, **kwargs): # real signature unknown
 70         """a.issubset(b) a是否是b的子集 相當於 a <= b"""
 71         """ Report whether another set contains this set. """
 72         pass
 73 
 74     def issuperset(self, *args, **kwargs): # real signature unknown
 75         """a.issubset(b) a是否是b的父集 相當於 a > b"""
 76         """ Report whether this set contains another set. """
 77         pass
 78 
 79     def pop(self, *args, **kwargs): # real signature unknown
 80         """隨機刪除一個元素"""
 81         """
 82         Remove and return an arbitrary set element.
 83         Raises KeyError if the set is empty.
 84         """
 85         pass
 86 
 87     def remove(self, *args, **kwargs): # real signature unknown
 88         """指定一個元素刪除,只能有一個元素;刪除元素不存在會報錯"""
 89         """
 90         Remove an element from a set; it must be a member.
 91 
 92         If the element is not a member, raise a KeyError.
 93         """
 94         pass
 95 
 96     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 97         """交叉差集; 兩個集合;相當於先並集再去除他們相同的元素; a ^ b"""
 98         """
 99         Return the symmetric difference of two sets as a new set.
100 
101         (i.e. all elements that are in exactly one of the sets.)
102         """
103         pass
104 
105     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
106         """交叉差集更新; 兩個集合;相當於先並集再去除他們相同的元素;a = a ^ b"""
107         """ Update a set with the symmetric difference of itself and another. """
108         pass
109 
110     def union(self, *args, **kwargs): # real signature unknown
111         """求並集 相當於 return a | b"""
112         """
113         Return the union of sets as a new set.
114 
115         (i.e. all elements that are in either set.)
116         """
117         pass
118 
119     def update(self, *args, **kwargs): # real signature unknown
120         """更新 元素,可以更新多個值,但是'int' object is not iterable;相當於 a = a | b"""
121         """ Update a set with the union of itself and others. """
122         pass
set

 

1.3集合的關系運算

in , not in

==, != , <=, <, >=, >

|, |= : 並集

&, &= : 交集

-, -= : 差集

^, ^= : 交叉差集

2.字符串格式化

 

Python中字符串格式有兩種:百分號方式,format方式。

2.2百分號字符串的拼接

%[(name)][flags][width].[precision]typecode

  • name    可選,用於指定的key
  • flags     可選,
    •     +(右對齊前面加符號)
    •      -(左對齊,正數無符號,負數有)
    •      空格(右對齊,正數前加空格,負數前負號)
    •      0(左對齊,正數無符號,負數有;用0填充空白處)
  • width    可選,占有的寬度
  • precision         小數點后保留的位數
  • typecode         必選,格式類型

常用格式

 

 1 tp = "i am a %s"%"boy"
 2 
 3 tp = "i am a %s,age %d"%("boy",18)
 4 
 5 tp = "i am a %(sex)s,age %(age)d"%{"sex":"boy","age":18}
 6 
 7 tp = "percent %.2f"%99.888
 8 
 9 tp = "percent %(p).2f"%{"p":123.456}
10 
11 tp = "percent %(p).2f%%"%{"p":123.456} #在字符串中連續兩個%是表示百分號

 

2.3Format方式

 

[[fill]align][sign][#][0][width][,][.precision][type]

  • fill                        可選,空白處填充的字符
  • aligh                    可選,對齊方式,需要與width配合使用
    • <               內容左對齊
    • >               內容右對齊(默認)
    • =               內容左對齊,將符號放在填充字符的左側
    • ^                內容居中
  • sign                     可選 ,有無符號數字
    • +               正數加+,負數加-
    • -                正數不變,負數加-
    • 空格          正數加空格,負數加-
  • #                          可選,對於二,八,十六進制,如果加上#,會顯示0b/0o/0x/否則不顯示
  • ,                           可選,數字添加分隔符  如 100,000
  • width                   可選,位寬
  • .precision            可選,保留小數點后位數
  • type                     可選,格式化類型

常用格式:

 

 1 tp = "i am a {}, age {}, {}".format("boy",18,"abc")
 2 
 3 tp = "i am a {0}, age {0}, {2}".format("boy",18,"abc")
 4 
 5 tp = "i am a {1}, age {0}, {2}".format("boy",18,"abc")
 6 
 7 tp = "i am a {sex}, age {age}, {abc}".format(sex="boy",age=18,abc="abc")
 8 
 9 tp = "i am a {sex}, age {age}, {abc}".format(**{"sex":"boy","age":18,"abc":"abc"})
10 
11 tp = "i am a {0}, age {0[0]}, {0[0]}".format([1,2,3],[4,5,6])
12 
13 tp = "i am a {:s}, age {:d}, {:f}".format("boy",18,18.123)
14 
15 tp = "i am a {:s}, age {:d}, {:f}".format(*["boy",18,18.123])
16 
17 tp = "i am a {sex:s}, age {age:d}, {abc:f}".format(**{"sex":"boy","age":18,"abc":18.123})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM