国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Python集合操作總結(jié)

Jioby / 457人閱讀

摘要:需要使用與區(qū)別八進(jìn)制,十六進(jìn)制。但,像多帶帶一個(gè),既可以是十六進(jìn)制,也可以是八進(jìn)制,無須轉(zhuǎn)義一般情況,我們無須關(guān)注底層一個(gè)字符花費(fèi)多少。避免使用此法實(shí)例,用不建議,方法會(huì)創(chuàng)建返回?cái)?shù)組,降低效率

Google"s Python Course

List

List變量是可變的(mutable)
官方文檔

1. 操作
squares = [1, 4, 9, 16, 25]
squares[-1]   # 25
squares[-3:]  # returns a new list [9, 16, 25]
squares[1:3]  # returns a new list [4, 9]
squares[:]    # returns a new (shallow) copy [1, 4, 9, 16, 25]
squares + [36, 49, 64, 81, 100]  # concatenation, return a new list
squares[0] = 0     # replaces the value
squares[len(squares):] = [36]  # appends a "36"
squares[1:3] = []  # removes [4, 9]
squares[:] = []    # clears the list -> del squares[:]
squares *= 2       # 元素重復(fù)2次,[1, 4, 9, 16, 25, 1, 4, 9, 16, 25]

判斷l(xiāng)ist是否為空:不要用len(seq) 參看PEP8

if not seq:
if seq:
2.方法

操作在原數(shù)組上進(jìn)行,不像concatenation一樣返回新數(shù)組

sum([1,2,3,4])  # 10
max([1,2,3,4])  # 4
list.append(x)  # equivalent to a[len(a):] = [x], x是元素
list.extend(iterable)  # equivalent to a[len(a):] = iterable, iterable是數(shù)組
list.remove(x)  # x是元素
list.pop([i])  # 默認(rèn)刪除最后一個(gè)元素, i表示index, []表示可選
list.clear()
list.index(x[, start[, end]])  # 返回元素x的index
list.count(x)  # 返回元素x個(gè)數(shù)
list.sort(key=None, reverse=False)
"""
"key=" specifying a "key" function that transforms each element before comparison. 
The key function takes in 1 value and returns 1 value, 
and the returned "proxy" value is used for the comparisons within the sort.
"""
list.sort(key=len)   # 先得到每個(gè)元素的len,然后根據(jù)len排序
list.reverse()
list.copy()  # Return a shallow copy of the list. Equivalent to a[:]

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. This is a design principle for all mutable data structures in Python.

3.數(shù)據(jù)結(jié)構(gòu)
# 隊(duì)列
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.popleft()                 # The first to arrive now leaves
4.列表推導(dǎo) List Comprehensions
[x**2 for x in range(10)]

[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
# 注意for、if的順序
combs = []
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            combs.append((x, y))
>>>combs
# flatten a list
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem]
flatten = []
for elem in vec:
    for num in elem:
        flatten.append(num)
>>>flatten
# 矩陣倒置
# 但是最好使用list(zip(*matrix))
matrix = [
            [1, 2, 3, 4],
            [5, 6, 7, 8],
            [9, 10, 11, 12],
         ]
[[row[i] for row in matrix] for i in range(4)]

# !!! 變量使用之前要像這樣聲明一遍
transposed = []
for i in range(4):
    transposed.append([row[i] for row in matrix])
>>> transposed

transposed = []
for i in range(4):
    # the following 3 lines implement the nested listcomp
    transposed_row = []
        for row in matrix:
            transposed_row.append(row[i])
    transposed.append(transposed_row)
>>> transposed
String

String變量是不可變的(immutable)

"doesn"t"  # 等價(jià) "doesn"t"
print("C:some
ame")   # C:some            ame
print(r"C:some
ame")  # r表示raw, C:some
ame

# print多行
print("""
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

3 * "un" + "ium"  # "unununium"
"Py" "thon"  # "Python", 非常有用,用于分解多行
text = ("Put several strings within parentheses "
        "to have them joined together.")
# 以上方法,不能用于變量(或表達(dá)式) 與 字符串的連接。需要使用+

String 與 bytes 區(qū)別:
o12 八進(jìn)制,x0a十六進(jìn)制。但,像多帶帶一個(gè)"a",既可以是十六進(jìn)制,也可以是八進(jìn)制,無須轉(zhuǎn)義
一般情況,我們無須關(guān)注底層一個(gè)字符花費(fèi)多少byte。只有在需要將string編碼(encode)成byte的時(shí)候,比如:通過網(wǎng)絡(luò)傳輸數(shù)據(jù);或者需要將byte解碼(decode)成string的時(shí)候,我們才會(huì)關(guān)注string和byte的區(qū)別。

a = "€20".encode("utf-8")
b = b"xe2x82xac20".decode("utf-8")
1.方法
s = "abc"
s.center(10, "@")   # @@@abc@@@@
s.count("a")        # 1
s.encode("utf-8")   # b"abc"
s.endswith("b")     # False
s.startswith(("a","A"))   # 傳入tuple,用于查詢
"1,2,3,4".split(",", 2)   # ["1", "2", "3,4"]
"abc	abc".expandtabs()      # len = 8 + 3,	補(bǔ)足八位
s.find("b")         # retuen the lowest index. 注意:總是用"b" in s來判斷是否是子串
s.rfind("b")         # retuen the highest index.
"The jack is {1}".format(1, 2, 3)
"The jack is {1}".format(*[1, 2, 3])
"The jack is {jack}".format(jack=4098, sape=4139)
"The jack is {jack}".format(**{"jack": 4098, "sape": 4139})
s.index("d")   # 等同于find;raise ValueError
s.join("de")        # return a new sttring "abcde"
s.ljust(5, "@")      # abc@@ 補(bǔ)充右側(cè)
s.rjust(5, "@")      # @@abc 補(bǔ)充左側(cè)
s.strip("ab")
s.lstrip("123a")          # specifying the set of characters to be removed; If none para, removing whitespace
s.rstrip("123c")          # "ab"
s.partition("b")          # return a tuple ("a", "b", "c"),第一個(gè)出現(xiàn)的b
s.rpartition("b")         # return a tuple ("a", "b", "c"),最后一個(gè)出現(xiàn)的b
s.replace("a","A")        # replace(old, new[, count]) 替代第count個(gè)old字符串替換為new,count從1開始
"ab c

de fg
kl
".splitlines()  # ["ab c", "", "de fg", "kl"]
"www.example.com".strip("cmowz.")     # The outermost leading and trailing chars argument values are stripped from the string
2.format方法

Mostly used to combine Number with String, e.g. "Key1"
Format strings contain “replacement fields” surrounded by curly braces {}. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

class a:

    def __init__(self):
        self._x = 10
        self._y = 45

a = a()
"y is {0._y}, x is {0._x}".format(a)   # y is 45, x is 10
b = [45, 10]
"y is {0[0]}, x is {0[1]}".format(b)
"y is {arg[0]}, x is {arg[1]}".format(arg = b)
"array is {0!r}".format(b)    # array is [45, 10]
# Three conversion flags : "!s" which calls str() on the value, 
#"!r" which calls repr() and "!a" which calls ascii().
"int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)  
# 只接受數(shù)字
# "int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010"

points = 19
total = 22
"Correct answers: {:.2%}".format(points/total)  # 86.36%

import datetime
d = datetime.datetime(2010, 7, 4, 12, 15, 58)
"{:%Y-%m-%d %H:%M:%S}".format(d)
3.Template strings
from string import Template

t = Template("$who likes $whom")

t.substitute(who="Jam", whom="Mo")  # Jam likes Mo
d = dict(who="Jam", whom="Mo")
t.substitute(d)

t.safe_substitute(who="Jam")   # Jam likes $whom
numbers.Number

The numbers module (PEP 3141) defines a hierarchy of numeric abstract base classes.

Number :> Complex :> Real :> Rational :> Integral, where A :> B means "A is a supertype of B".

Python supports arbitrarily large integers.

Bytes,Bytearray

byte對(duì)象是不可變的(immutable)
bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256

Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data

bytearray objects are a mutable counterpart to bytes objects

b = b"€20"   # SyntaxError
bytes.fromhex("30")   # b"0", fromhex()類方法class method

bytes.fromhex("303132")  # b"012",十六進(jìn)制
bytes([50,51,52])        # b"234",十進(jìn)制。避免使用此法實(shí)例bytes,用b""
Tuple

Tuples are immutable

t = (12345, 54321, "hello!")
t[0]  # 12345
Set

A set is an unordered collection with no duplicate elements

basket = {"apple", "orange", "apple", "pear", "orange", "banana"}
"orange" in basket

a = set("abracadabra")
b = set("alacazam")
a-b   # letters in a but not in b
a|b   # letters in a or b or both
a&b   # letters in both a and b
a^b   # letters in a or b but not both

{x for x in "abracadabra" if x not in "abc"}
Dictionary
tel = {"jack": 4098, "sape": 4139}
tel.keys()
tel.values()
tel["guido"] = 4127
"guido" in tel    # True
"guido" in tel.keys() # 不建議,keys方法會(huì)創(chuàng)建返回key數(shù)組,降低效率

{x: x**2 for x in (2, 4, 6)}

d = dict(sape=4139, guido=4127, jack=4098)
for k, v in d.items():
    print(k, v)

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/44587.html

相關(guān)文章

  • Python入門-高級(jí)數(shù)據(jù)結(jié)構(gòu)

    摘要:下面讓我們一塊來看下的中高級(jí)數(shù)據(jù)結(jié)構(gòu)。到現(xiàn)在,我們學(xué)習(xí)了列表元組字典和集合種高級(jí)數(shù)據(jù)結(jié)構(gòu)。 < 返回索引頁 高級(jí)數(shù)據(jù)結(jié)構(gòu) 列表與元組 什么是列表 列表的操作 什么是元組 元組的操作 字典與集合 字典的定義 字典的操作 集合的定義 集合的操作 序列 序列的通用操作 可變類型和不可變類型 深copy和淺copy 總結(jié) 練習(xí) 參考 高級(jí)數(shù)據(jù)結(jié)構(gòu) 我們知道P...

    jayzou 評(píng)論0 收藏0
  • Python零基礎(chǔ)到入門】Python基礎(chǔ)語法篇——基本數(shù)據(jù)類型【文末送書】

    摘要:布爾值布爾值和布爾代數(shù)的表示完全一致,一個(gè)布爾值只有兩種值的數(shù)據(jù)類型可以通過內(nèi)置的函數(shù)查詢,例如還可以用來判斷和的區(qū)別在于不會(huì)認(rèn)為子類是一種父類類型。會(huì)認(rèn)為子類是一種父類類型。基本功能是進(jìn)行成員關(guān)系測(cè)試和刪除重復(fù)元素。 ...

    Winer 評(píng)論0 收藏0
  • 「碼個(gè)蛋」2017年200篇精選干貨集合

    摘要:讓你收獲滿滿碼個(gè)蛋從年月日推送第篇文章一年過去了已累積推文近篇文章,本文為年度精選,共計(jì)篇,按照類別整理便于讀者主題閱讀。本篇文章是今年的最后一篇技術(shù)文章,為了讓大家在家也能好好學(xué)習(xí),特此花了幾個(gè)小時(shí)整理了這些文章。 showImg(https://segmentfault.com/img/remote/1460000013241596); 讓你收獲滿滿! 碼個(gè)蛋從2017年02月20...

    wangtdgoodluck 評(píng)論0 收藏0
  • ??爆肝十二萬字《python從零到精通教程》,從零教你變大佬??(建議收藏)

    文章目錄 強(qiáng)烈推薦系列教程,建議學(xué)起來!! 一.pycharm下載安裝二.python下載安裝三.pycharm上配置python四.配置鏡像源讓你下載嗖嗖的快4.1pycharm內(nèi)部配置 4.2手動(dòng)添加鏡像源4.3永久配置鏡像源 五.插件安裝(比如漢化?)5.1自動(dòng)補(bǔ)碼神器第一款5.2漢化pycharm5.3其它插件 六.美女背景七.自定義腳本開頭八、這個(gè)前言一定要看九、pyt...

    booster 評(píng)論0 收藏0
  • Python 進(jìn)階之路 (四) 先立Flag, 社區(qū)最全的Set用法集錦

    摘要:與上面的操作類似,可以使用多種運(yùn)算符和方法來更改集合的內(nèi)容。通過修改集合元素方法運(yùn)算符用法通過修改集合和作用是向集合中添加中所有不存在的元素。 Set是什么 大家好,恰逢初五迎財(cái)神,先預(yù)祝大家新年財(cái)源滾滾!!在上一期詳解tuple元組的用法后,今天我們來看Python里面最后一種常見的數(shù)據(jù)類型:集合(Set) 與dict類似,set也是一組key的集合,但不存儲(chǔ)value。由于key不...

    nodejh 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<