资讯专栏INFORMATION COLUMN

Python集合操作总结

Jioby / 373人阅读

摘要:需要使用与区别八进制,十六进制。但,像多带带一个,既可以是十六进制,也可以是八进制,无须转义一般情况,我们无须关注底层一个字符花费多少。避免使用此法实例,用不建议,方法会创建返回数组,降低效率

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       # 元素重复2次,[1, 4, 9, 16, 25, 1, 4, 9, 16, 25]

判断list是否为空:不要用len(seq) 参看PEP8

if not seq:
if seq:
2.方法

操作在原数组上进行,不像concatenation一样返回新数组

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是数组
list.remove(x)  # x是元素
list.pop([i])  # 默认删除最后一个元素, i表示index, []表示可选
list.clear()
list.index(x[, start[, end]])  # 返回元素x的index
list.count(x)  # 返回元素x个数
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)   # 先得到每个元素的len,然后根据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.数据结构
# 队列
from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.popleft()                 # The first to arrive now leaves
4.列表推导 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"  # 等价 "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.")
# 以上方法,不能用于变量(或表达式) 与 字符串的连接。需要使用+

String 与 bytes 区别:
o12 八进制,x0a十六进制。但,像多带带一个"a",既可以是十六进制,也可以是八进制,无须转义
一般情况,我们无须关注底层一个字符花费多少byte。只有在需要将string编码(encode)成byte的时候,比如:通过网络传输数据;或者需要将byte解码(decode)成string的时候,我们才会关注string和byte的区别。

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,	补足八位
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@@ 补充右侧
s.rjust(5, "@")      # @@abc 补充左侧
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"),第一个出现的b
s.rpartition("b")         # return a tuple ("a", "b", "c"),最后一个出现的b
s.replace("a","A")        # replace(old, new[, count]) 替代第count个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)  
# 只接受数字
# "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对象是不可变的(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",十六进制
bytes([50,51,52])        # b"234",十进制。避免使用此法实例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方法会创建返回key数组,降低效率

{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)

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/44587.html

相关文章

  • Python入门-高级数据结构

    摘要:下面让我们一块来看下的中高级数据结构。到现在,我们学习了列表元组字典和集合种高级数据结构。 < 返回索引页 高级数据结构 列表与元组 什么是列表 列表的操作 什么是元组 元组的操作 字典与集合 字典的定义 字典的操作 集合的定义 集合的操作 序列 序列的通用操作 可变类型和不可变类型 深copy和浅copy 总结 练习 参考 高级数据结构 我们知道P...

    jayzou 评论0 收藏0
  • Python零基础到入门】Python基础语法篇——基本数据类型【文末送书】

    摘要:布尔值布尔值和布尔代数的表示完全一致,一个布尔值只有两种值的数据类型可以通过内置的函数查询,例如还可以用来判断和的区别在于不会认为子类是一种父类类型。会认为子类是一种父类类型。基本功能是进行成员关系测试和删除重复元素。 ...

    Winer 评论0 收藏0
  • 「码个蛋」2017年200篇精选干货集合

    摘要:让你收获满满码个蛋从年月日推送第篇文章一年过去了已累积推文近篇文章,本文为年度精选,共计篇,按照类别整理便于读者主题阅读。本篇文章是今年的最后一篇技术文章,为了让大家在家也能好好学习,特此花了几个小时整理了这些文章。 showImg(https://segmentfault.com/img/remote/1460000013241596); 让你收获满满! 码个蛋从2017年02月20...

    wangtdgoodluck 评论0 收藏0
  • ❤️爆肝十二万字《python从零到精通教程》,从零教你变大佬❤️(建议收藏)

    文章目录 强烈推荐系列教程,建议学起来!! 一.pycharm下载安装二.python下载安装三.pycharm上配置python四.配置镜像源让你下载嗖嗖的快4.1pycharm内部配置 4.2手动添加镜像源4.3永久配置镜像源 五.插件安装(比如汉化?)5.1自动补码神器第一款5.2汉化pycharm5.3其它插件 六.美女背景七.自定义脚本开头八、这个前言一定要看九、pyt...

    booster 评论0 收藏0
  • Python 进阶之路 (四) 先立Flag, 社区最全的Set用法集锦

    摘要:与上面的操作类似,可以使用多种运算符和方法来更改集合的内容。通过修改集合元素方法运算符用法通过修改集合和作用是向集合中添加中所有不存在的元素。 Set是什么 大家好,恰逢初五迎财神,先预祝大家新年财源滚滚!!在上一期详解tuple元组的用法后,今天我们来看Python里面最后一种常见的数据类型:集合(Set) 与dict类似,set也是一组key的集合,但不存储value。由于key不...

    nodejh 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<