• ==用于比较两个对象的值是否相等,is用于比较两个对象的id值是否相等,即是否位于同一地址。
  • bool(-6) # => True
  • -5 != False # => True
  • -5 or 0 # => -5
  • 2 < 3 < 2 # => False
# Strings can be added too
"Hello " + "world!"  # => "Hello world!"
# String literals (but not variables) can be concatenated without using '+'
"Hello " "world!"    # => "Hello world!"
# You can find the length of a string
len("This is a string")  # => 16
# Don't use the equality "==" symbol to compare objects to None
# Use "is" instead. This checks for equality of object identity.
"etc" is None  # => False
None is None   # => True

print的可选参数

# By default the print function also prints out a newline at the end.
# Use the optional argument end to change the end string.
print("Hello, World", end="!")  # => Hello, World!

if,else可以作为表达式

# if can be used as an expression
# Equivalent of C's '?:' ternary operator
"yay!" if 0 > 1 else "nay!"  # => "nay!"

列表

  • 列表中的元素类型可以是不同的
  • 列表的元素用,分隔,最后,之后再添加空格,优化代码风格

列表的append和pop方法

# Add stuff to the end of a list with append
li.append(1)    # li is now [1]
li.append(2)    # li is now [1, 2]
li.append(4)    # li is now [1, 2, 4]
li.append(3)    # li is now [1, 2, 4, 3]
# Remove from the end with pop
li.pop()        # => 3 and li is now [1, 2, 4]
# Let's put it back
li.append(3)    # li is now [1, 2, 4, 3] again.

列表的切片

li[::2]   # Return list selecting elements with a step size of 2 => [1, 4]
li[::-1]  # Return list in reverse order => [3, 4, 2, 1]
# li[start:end:step]
  • list两个冒号的用法(numpy数组类似)
  • 第一个index指定开始,第二个index指定结束,第三个指定间隔
ls = list(range(100))

ls[0:100:10]
# [out]:[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

删除列表中的元素

# 按位置删除
# Remove arbitrary elements from a list with "del"
del li[2]  # li is now [1, 2, 3]

# 按值删除
# Remove first occurrence of a value
li.remove(2)  # li is now [1, 3]
li.remove(2)  # Raises a ValueError as 2 is not in the list

清空列表

li.clear()  # Remove all elements from the list

删除列表对象

del li  # Delete the list object

在列表中插入元素

# 第一个参数为位置,第二个参数为值
# Insert an element at a specific index
li.insert(1, 2)  # li is now [1, 2, 3] again

列表加法

# You can add lists
# Note: values for li and for other_li are not modified.
li + other_li  # => [1, 2, 3, 4, 5, 6]

# Concatenate lists with "extend()"
li.extend(other_li)  # Now li is [1, 2, 3, 4, 5, 6]

列表的其他操作

# Check for existence in a list with "in"
1 in li  # => True

# Examine the length with "len()"
len(li)  # => 6

元组

  • 类似列表但是不能更改值:没有append()方法
  • 但是有定义加法这很奇怪:产生了一个新的元组,但是原来的元组并没有被改变
tup = (1, 2, 3)
tup[0]      # => 1
tup[0] = 3  # Raises a TypeError
list = [1, 2, 3]

tu = tuple(list); print(tu) # => (1, 2, 3)
tu += (4,); print(tu) # => (1, 2, 3, 4)
  • 元组的小陷阱
# Note that a tuple of length one has to have a comma after the last element but
# tuples of other lengths, even zero, do not.
type((1))   # => <class 'int'>
type((1,))  # => <class 'tuple'>
type(())    # => <class 'tuple'>

使用与列表的操作在元组上一般都能使用

元组的解包

# You can unpack tuples (or lists) into variables
a, b, c = (1, 2, 3)  # a is now 1, b is now 2 and c is now 3
# You can also do extended unpacking
a, *b, c = (1, 2, 3, 4)  # a is now 1, b is now [2, 3] and c is now 4
# Tuples are created by default if you leave out the parentheses
d, e, f = 4, 5, 6  # tuple 4, 5, 6 is unpacked into variables d, e and f
# respectively such that d = 4, e = 5 and f = 6
# Now look how easy it is to swap two values
e, d = d, e  # d is now 5 and e is now 4

字典

左key右value

  • 为了保证字典的正确性和稳定性,键需要是不可变类型,常见的不可变类型包括整数、浮点数、字符串、元组,因为这些类型在创建后其值不能被改变,这样可以确保字典的键在使用过程中保持唯一性和稳定性。value可以是任何类型

字典的查看:[]

# Look up values with []
filled_dict["one"]  # => 1

字典的快捷构造方法

  • 可以使用任何输出序对的迭代器构造字典
dict(enumerate("abcd"))

直接对字典进行迭代,输出的是Key

使用“keys()”、“values()”方法获取所有键作为可迭代对象。我们需要将其调用用 list() 包裹起来,将其转换为列表。

list(filled_dict.keys()) 
list(filled_dict.values()) 

items()方法,将键值对一起迭代

for key, value in filled_dict.items():
    print(key, value)

使用get()方法避免KeyError,还可以设置defult值

# Looking up a non-existing key is a KeyError
filled_dict["four"]  # KeyError

# Use "get()" method to avoid the KeyError
filled_dict.get("one")      # => 1
filled_dict.get("four")     # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4)   # => 1
filled_dict.get("four", 4)  # => 4

setdefault()方法

  • 先检查字典中是否存在“key”这个键。如果不存在,就会将“key”和对应的“value”插入到字典中;如果“key”已经存在,那么就不会插入,字典保持不变。
filled_dict.setdefault("five", 5)  # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6)  # filled_dict["five"] is still 5

字典的删除:del,dic = {},dic.pop(keys),dic.popitem()

字典的更新

# Adding to a dictionary
filled_dict.update({"four":4})  # => {"one": 1, "two": 2, "three": 3, "four": 4}
filled_dict["four"] = 4         # another way to add to dict

# Remove keys from a dictionary with del
del filled_dict["one"]  # Removes the key "one" from filled dict

字典的作用:条件语句字典化

aff = '工物'
if aff == '工物':
    print(20)
elif aff == '物理':
    print(40)
elif aff == "上海交大":
    print(2)
else:
    print(1)

# 用字典查询更加方便
print(sc[aff])

set集合

集合的声明

empty_set = set()
# Initialize a set with a bunch of values.
some_set = {1, 1, 2, 2, 3, 4}  # some_set is now {1, 2, 3, 4}

集合中的元素可以是不同类型的,但是必须是不可变类型

invalid_set = {[1], 1}  # => Raises a TypeError: unhashable type: 'list'
valid_set = {(1,), 1}

集合中添加元素

# Add one more item to the set
filled_set = some_set
filled_set.add(5)  # filled_set is now {1, 2, 3, 4, 5}
# Sets do not have duplicate elements
filled_set.add(5)  # it remains as before {1, 2, 3, 4, 5}

集合之间的交并补运算

  • 集合取交集
# Do set intersection with &
other_set = {3, 4, 5, 6}
filled_set & other_set  # => {3, 4, 5}
  • 集合取并集
# Do set union with |
filled_set | other_set  # => {1, 2, 3, 4, 5, 6}
  • 集合取补集
# Do set difference with -
{1, 2, 3, 4} - {2, 3, 5}  # => {1, 4}

# Do set symmetric difference with ^
{1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}
  • 集合的包含关系
# Check if set on the left is a superset of set on the right
{1, 2} >= {1, 2, 3}  # => False

# Check if set on the left is a subset of set on the right
{1, 2} <= {1, 2, 3}  # => True
  • 集合是可变的
A = {1, 2, 3}
A.add(4)  # A is now {1, 2, 3, 4}
A.discard(2)  # A is now {1, 3, 4}
A.clear()  # A is now set()
A.pop()

字符串

  • str.strip()方法:移除字符串首尾的指定字符(默认空白符)

defaultdict–带有默认值的字典

from collections import defaultdict
dsc = defaultdict(int)
  • The default factory is called without arguments to produce a new value when a key is not present, in getitem only. A defaultdict compares equal to a dict with the same items. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

Counter–计数器

  • Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.
eps = ["物理","物理","工物","工物","物理"]
from collections import Counter
 cnumbers = Counter(deps)
 print(cnumbers)
  • Counter({'物理':3,'工物':2})

带名字的tuple

alt text


一些其他很python的用法

list comprehensions列表推导式

[add_10(i) for i in [1, 2, 3]]         # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5]  # => [6, 7]
  • 集合和字典都可以如此使用
{x for x in "abcddeef" if x not in "abc"}  # => {'d', 'e', 'f'}
{x: x**2 for x in range(5)}  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}