Python数据类型和常见操作

Python Data Types and Structures

Strings

Strings are immutable sequence objects, with each character representing an element in the sequence. As with all objects, we use methods to perform operations. Strings, being immutable, do not change the instance; each method simply returns a value. This value can be stored as another variable or given as an argument to a function or method.

MethodsDescriptions
s.count(substring, [start,end])Counts the occurrences of a substring with optional start and end parameters.
s.expandtabs([tabsize])Replaces tabs with spaces.
s.find(substring, [start, end])Returns the index of the first occurrence of a substring or returns -1 if the substring is not found.
s.isalnum()Returns True if all characters are alphanumeric, returns False otherwise.
s.isalpha()Returns True if all characters are alphabetic, returns False otherwise.
s.isdigit()Returns True if all characters are digits, returns False otherwise.
s.join(t)Joins the strings in sequence t .
s.lower()Converts the string to all lowercase.
s.replace(old, new [maxreplace])Replaces old substring with new substring.
s.strip([characters])Removes whitespace or optional characters.
s.split([separator], [maxsplit])Splits a string separated by whitespace or an optional separator. Returns a list.

List

MethodDescription
list(s)Returns a list of the sequence s.
s.append(x)Appends element x to the end of s.
s.extend(x)Appends the list x to s.
s.count(x)Counts the occurrence of x in s.
s.index(x, [start], [stop])Returns the smallest index, i , where s[i] == x. Can include optional start and stop index for the search.
s.insert(i,e)Inserts x at index i.
s.pop(i)Returns the element i and removes it from the list.
s.remove(x)Removes x from s.
s.reverse()Reverses the order of s.
s.sort(key ,[reverse])Sorts s with optional key and reverse.

Operations and expressions

在Python中以下的值被认为是False:

  • None类型
  • False
  • integer,float, complex 的 zero
  • 空的序列或者map
  • 用户定义的类的实例中诸如__len__()、bool()等方法返回值是0或者False。

此外,其他值均被当作True。

Boolean operations

OperatorExample
not xReturns True if x is False ; returns False otherwise.
x and yReturns True if both x and y are True ; returns False otherwise.
x or yReturns True if either x or y is True ; returns False otherwise.

Build-in data types

CategoryNameDescription
NoneNoneThe null object.
NumericintInteger.
floatFloating point number.
complexComplex number.
boolBoolean (True, False).
SequencesstrString of characters.
listList of arbitrary objects.
TupleGroup of arbitrary items.
rangeCreates a range of integers.
MappingdictDictionary of key-value pairs.
setMutable, unordered collection of unique items.
frozensetImmutable set.

Sequences

MethodDescription
len(s)Number of elements in s
min(s, [,default=obj, key=func])The minimum value in s (alphabetically for strings)
max(s, [,default=obj, key=func])Maximum value in s (alphabetically for strings)
sum(s,[,start=0])The sum of the elements (returns TypeError if s is not numeric)
all(s)Returns True if all elements in s are True (that is, not 0 , False , or Null )
any(s)Checks whether any item in s is True
OperationDescription
s + rConcatenates two sequences of the same type
s * nMake n copies of s , where n is an integer
v1, v2 ..., vn = sUnpacks n variables from s to v1 , v2 , and so on
s[i]Indexing-returns element i of s
s[i:j:stride]Slicing returns elements between i and j with optional stride
x in sReturns True if element x is in s
x not in sReturns true if element x is not in s

Dictionaries

MethodDescription
len(d)Number of items in d.
d.clear()Removes all items from d.
d.copy()Makes a shallow copy of d.
d.fromkeys(s [,value])Returns a new dictionary with keys from sequence s and values set to value.
d.get(k [,v])Returns d[k] if found, or else returns v , or None if v is not given.
d.items()Returns a sequence of key:value pairs in d.
d.keys()Returns a sequence of keys in d.
d.pop(k [,default])Returns d[k] and removes it from d . If d[k] is not found, it returns default or raises KeyError.
d.popitem()Removes a random key:value pair from d and returns it as a tuple.
d.setdefault(k [,v])Returns d[k] . If d[k] is not found, it returns v and sets d[k] to v.
d.update(b)Adds all objects from b to d.
d.values()Returns a sequence of values in d.

Sets

Methods and operations of sets are described in the following table:

MethodOperatorsDescription
len(s)Returns the number of elements in s
s.copy()Returns a shallow copy of s
s.difference(t)s - t- t2 -...Returns a set of all items in s but not in t
s.intersection(t)Returns a set of all items in both t and s
s.isdisjoint(t)Returns True if s and t have no items in common
s.issubset(t)s <= t s < t (s != t)Returns True if all items in s are also in t
s.issuperset(t)s >= t s > t (s != t)Returns True if all items in t are also in s
s.symmetric_difference(t)s ^ tReturns a set of all items that are in s or t , but not both
s.union(t)s | t1 | t2|...Returns a set of all items in s or t

Mutable set objects have additional methods, described in the following table:

MethodDescription
s.add(item)Adds item to s . Has no effect if item is already present.
s.clear()Removes all items from s.
s.difference_update(t)Removes all items in s that are also in t.
s.discard(item)Removes item from s.
s.intersection_update(t)Removes all items from s that are not in the intersection of s and t.
s.pop()Returns and removes an arbitrary item from s.
s.remove(item)Removes item from s.
s.symetric_difference_update(t)Removes all items from s that are not in the symmetric difference of s and t.
s.update(t)Adds all the items in an iterable object t to s.

Modules for data structures and algorithms

Collections

The collections module provides more specialized, high, performance alternatives for
the built-in data types as well as a utility function to create named tuples. The following
table lists the datatypes and operations of the collections module and their descriptions:

Datatype or operationDescription
namedtuple()Creates tuple subclasses with named fields.
dequeLists with fast appends and pops either end.
ChainMapDictionary like class to create a single view of multiple mappings.
CounterDictionary subclass for counting hashable objects.
OrderedDictDictionary subclass that remembers the entry order.
defaultdictDictionary subclass that calls a function to supply missing values.
UserDict UserList UserStringThese three data types are simply wrappers for their underlying base classes. Their use has largely been supplanted by the ability to subclasas their respective base classes directly. Can be used to access the underlying object as an attribute.

Array

The array objects support the following attributes and methods:

Attribute or methodDescription
a.typecodeThe typecode character used to create the array.
a.itemsizeSize, in bytes, of items stored in the array.
a.append(x)Appends item x to the end of the array.
a.buffer_info()Returns the memory location and length of the buffer used to store the array.
a.byteswap()Swaps the byte order of each item. Used for writing to a machine orfile with a different byte order.
a.count(x)Returns the number of occurrences of x in a.
a.extend(b)Appends any iterable, b , to the end of array a.
a.frombytes(s)Appends items from a string, s , as an array of machine values.
a.fromfile(f, n)Reads n items, as machine values, from a file object, f , and appends them to a . Raises an EOFError if there are fewer than n items in n.
a.fromlist(l)Appends items from list l.
a.fromunicode(s)Extends a with unicode string s . Array a must be of type u or elseValueError is raised.
index(x)Returns the first (smallest) index of item x.
a.insert(i, x)Inserts item x before index i.
a.pop([i])Removes and returns items with index i. Defaults to the last item (i = -1) if not specified.
a.remove(x)Removes the first occurrence of item x.
a.reverse()Reverses the order of items.
a.tobytes()Convert the array to machine values and returns the bytes representation.
a.tofile(f)Writes all items, as machine values, to file object f.
a.tolist()Converts the array to a list.
a.tounicode()Convert an array to unicode string. The array type must be ‘u’ or else a ValueError is raised.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值