老是报错gre argument 错误x'must be numeric需要怎么改

python基础2
来源:博客园
内容概要:一、python2 or 3二、字符串拼接三、字符串四、列表、元祖五、字典六、集合七、练习 一、python2 or python3目前大多使用python2.7,随着时间的推移,python3将会成为python爱好者的主流。python2和3区别:1.PRINT IS A FUNCTION<span style="color: # Old: print "The answer is", 2*2 New: print("The answer is", 2*2)<span style="color: # Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline<span style="color: # Old: print # Prints a newline<span style="color: # New: print() # You must call the function!<span style="color: # Old: print &&sys.stderr, "fatal error" New: print("fatal error", file=sys.stderr)<span style="color: # Old: print (x, y) # prints repr((x, y))<span style="color: # New: print((x, y)) # Not the same as print(x, y)!2.某些库名改变例如:2.x3.x_winregwinregcopy_regcopyregQueuequeueSockerServersockerserverreprreprlib3.ALL IS UNICODE NOW所有的字符编码变为unicode 二、字符串拼接方法一:使用“+”(不推荐)原因:python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间name="wd"msg="my name is "+nameprint(msg)输出:my name is wd方法二:使用格式化字符串%s:字符串%d:整数%f:浮点数<span style="color: # name="wd"<span style="color: # age=22<span style="color: # job="IT"<span style="color: # msg="my name is %s age %d job %s"%(name,age,job)<span style="color: # print(msg)<span style="color: # 输出:<span style="color: # my name is wd age 22 job IT方法三:使用format进行格式化输出(变量名替换) 1 name="wd" 2 age=22 3 job="IT" 4 msg='''my name is:{_name} 5
age is: {_age} 6
job is: {_job}'''.format(_name=name,_age=age,_job=job) 7 print(msg) 8 输出: 9 my name is:wd<span style="color: #
age is: 22<span style="color: #
job is: IT或者:(位置替换) 1 name="wd" 2 age=22 3 job="IT" 4 msg='''my name is:{0} 5
age is: {1} 6
job is: {2}'''.format(name,age,job) 7 print(msg) 8 输出: 9 my name is:wd<span style="color: #
age is: 22<span style="color: #
job is: IT总结:对比以上三种方法,使用+方式进行拼接字符串会开辟较多的内存空间,效率低,推荐使用第二种和第三种方法。 三、字符串1.字符串常用操作移除空白(strip)分割(split)长度(len)索引(index)切片字符串对方法如下:
1 class str(basestring):
str(object='') -& string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
def capitalize(self):
""" 首字母变大写 """ 10
S.capitalize() -& string 12
Return a copy of the string S with only its first character 14
capitalized. 15
return "" 17
def center(self, width, fillchar=None):
""" 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """ 20
S.center(width[, fillchar]) -& string 22
Return S centered in a string of length width. Padding is 24
done using the specified fill character (default is a space) 25
return "" 27
def count(self, sub, start=None, end=None):
""" 子序列个数 """ 30
S.count(sub[, start[, end]]) -& int 32
Return the number of non-overlapping occurrences of substring sub in 34
string S[start:end].
Optional arguments start and end are interpreted 35
as in slice notation. 36
return 0 38
def decode(self, encoding=None, errors=None):
""" 解码 """ 41
S.decode([encoding[,errors]]) -& object 43
Decodes S using the codec registered for encoding. encoding defaults 45
to the default encoding. errors may be given to set a different error 46
handling scheme. Default is 'strict' meaning that encoding errors raise 47
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' 48
as well as any other name registered with codecs.register_error that is 49
able to handle UnicodeDecodeErrors. 50
return object() 52
def encode(self, encoding=None, errors=None):
""" 编码,针对unicode """ 55
S.encode([encoding[,errors]]) -& object 57
Encodes S using the codec registered for encoding. encoding defaults 59
to the default encoding. errors may be given to set a different error 60
handling scheme. Default is 'strict' meaning that encoding errors raise 61
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 62
'xmlcharrefreplace' as well as any other name registered with 63
codecs.register_error that is able to handle UnicodeEncodeErrors. 64
return object() 66
def endswith(self, suffix, start=None, end=None):
""" 是否以 xxx 结束 """ 69
S.endswith(suffix[, start[, end]]) -& bool 71
Return True if S ends with the specified suffix, False otherwise. 73
With optional start, test S beginning at that position. 74
With optional end, stop comparing S at that position. 75
suffix can also be a tuple of strings to try. 76
return False 78
def expandtabs(self, tabsize=None):
""" 将tab转换成空格,默认一个tab转换成8个空格 """ 81
S.expandtabs([tabsize]) -& string 83
Return a copy of S where all tab characters are expanded using spaces. 85
If tabsize is not given, a tab size of 8 characters is assumed. 86
return "" 88
def find(self, sub, start=None, end=None):
""" 寻找子序列位置,如果没找到,返回 -1 """ 91
S.find(sub [,start [,end]]) -& int 93
Return the lowest index in S where substring sub is found, 95
such that sub is contained within S[start:end].
Optional 96
arguments start and end are interpreted as in slice notation. 97
Return -1 on failure. 99
"""<span style="color: #0
return 0<span style="color: #1 <span style="color: #2
def format(*args, **kwargs): # known special case of str.format<span style="color: #3
""" 字符串格式化,动态参数,将函数式编程时细说 """<span style="color: #4
"""<span style="color: #5
S.format(*args, **kwargs) -& string<span style="color: #6
<span style="color: #7
Return a formatted version of S, using substitutions from args and kwargs.<span style="color: #8
The substitutions are identified by braces ('{' and '}').<span style="color: #9
"""<span style="color: #0
pass<span style="color: #1 <span style="color: #2
def index(self, sub, start=None, end=None):
<span style="color: #3
""" 子序列位置,如果没找到,报错 """<span style="color: #4
S.index(sub [,start [,end]]) -& int<span style="color: #5
<span style="color: #6
Like S.find() but raise ValueError when the substring is not found.<span style="color: #7
"""<span style="color: #8
return 0<span style="color: #9 <span style="color: #0
def isalnum(self):
<span style="color: #1
""" 是否是字母和数字 """<span style="color: #2
"""<span style="color: #3
S.isalnum() -& bool<span style="color: #4
<span style="color: #5
Return True if all characters in S are alphanumeric<span style="color: #6
and there is at least one character in S, False otherwise.<span style="color: #7
"""<span style="color: #8
return False<span style="color: #9 <span style="color: #0
def isalpha(self):
<span style="color: #1
""" 是否是字母 """<span style="color: #2
"""<span style="color: #3
S.isalpha() -& bool<span style="color: #4
<span style="color: #5
Return True if all characters in S are alphabetic<span style="color: #6
and there is at least one character in S, False otherwise.<span style="color: #7
"""<span style="color: #8
return False<span style="color: #9 <span style="color: #0
def isdigit(self):
<span style="color: #1
""" 是否是数字 """<span style="color: #2
"""<span style="color: #3
S.isdigit() -& bool<span style="color: #4
<span style="color: #5
Return True if all characters in S are digits<span style="color: #6
and there is at least one character in S, False otherwise.<span style="color: #7
"""<span style="color: #8
return False<span style="color: #9 <span style="color: #0
def islower(self):
<span style="color: #1
""" 是否小写 """<span style="color: #2
"""<span style="color: #3
S.islower() -& bool<span style="color: #4
<span style="color: #5
Return True if all cased characters in S are lowercase and there is<span style="color: #6
at least one cased character in S, False otherwise.<span style="color: #7
"""<span style="color: #8
return False<span style="color: #9 <span style="color: #0
def isspace(self):
<span style="color: #1
"""<span style="color: #2
S.isspace() -& bool<span style="color: #3
<span style="color: #4
Return True if all characters in S are whitespace<span style="color: #5
and there is at least one character in S, False otherwise.<span style="color: #6
"""<span style="color: #7
return False<span style="color: #8 <span style="color: #9
def istitle(self):
<span style="color: #0
"""<span style="color: #1
S.istitle() -& bool<span style="color: #2
<span style="color: #3
Return True if S is a titlecased string and there is at least one<span style="color: #4
character in S, i.e. uppercase characters may only follow uncased<span style="color: #5
characters and lowercase characters only cased ones. Return False<span style="color: #6
otherwise.<span style="color: #7
"""<span style="color: #8
return False<span style="color: #9 <span style="color: #0
def isupper(self):
<span style="color: #1
"""<span style="color: #2
S.isupper() -& bool<span style="color: #3
<span style="color: #4
Return True if all cased characters in S are uppercase and there is<span style="color: #5
at least one cased character in S, False otherwise.<span style="color: #6
"""<span style="color: #7
return False<span style="color: #8 <span style="color: #9
def join(self, iterable):
<span style="color: #0
""" 连接 """<span style="color: #1
"""<span style="color: #2
S.join(iterable) -& string<span style="color: #3
<span style="color: #4
Return a string which is the concatenation of the strings in the<span style="color: #5
The separator between elements is S.<span style="color: #6
"""<span style="color: #7
return ""<span style="color: #8 <span style="color: #9
def ljust(self, width, fillchar=None):
<span style="color: #0
""" 内容左对齐,右侧填充 """<span style="color: #1
"""<span style="color: #2
S.ljust(width[, fillchar]) -& string<span style="color: #3
<span style="color: #4
Return S left-justified in a string of length width. Padding is<span style="color: #5
done using the specified fill character (default is a space).<span style="color: #6
"""<span style="color: #7
return ""<span style="color: #8 <span style="color: #9
def lower(self):
<span style="color: #0
""" 变小写 """<span style="color: #1
"""<span style="color: #2
S.lower() -& string<span style="color: #3
<span style="color: #4
Return a copy of the string S converted to lowercase.<span style="color: #5
"""<span style="color: #6
return ""<span style="color: #7 <span style="color: #8
def lstrip(self, chars=None):
<span style="color: #9
""" 移除左侧空白 """<span style="color: #0
"""<span style="color: #1
S.lstrip([chars]) -& string or unicode<span style="color: #2
<span style="color: #3
Return a copy of the string S with leading whitespace removed.<span style="color: #4
If chars is given and not None, remove characters in chars instead.<span style="color: #5
If chars is unicode, S will be converted to unicode before stripping<span style="color: #6
"""<span style="color: #7
return ""<span style="color: #8 <span style="color: #9
def partition(self, sep):
<span style="color: #0
""" 分割,前,中,后三部分 """<span style="color: #1
"""<span style="color: #2
S.partition(sep) -& (head, sep, tail)<span style="color: #3
<span style="color: #4
Search for the separator sep in S, and return the part before it,<span style="color: #5
the separator itself, and the part after it.
If the separator is not<span style="color: #6
found, return S and two empty strings.<span style="color: #7
"""<span style="color: #8
pass<span style="color: #9 <span style="color: #0
def replace(self, old, new, count=None):
<span style="color: #1
""" 替换 """<span style="color: #2
"""<span style="color: #3
S.replace(old, new[, count]) -& string<span style="color: #4
<span style="color: #5
Return a copy of string S with all occurrences of substring<span style="color: #6
old replaced by new.
If the optional argument count is<span style="color: #7
given, only the first count occurrences are replaced.<span style="color: #8
"""<span style="color: #9
return ""<span style="color: #0 <span style="color: #1
def rfind(self, sub, start=None, end=None):
<span style="color: #2
"""<span style="color: #3
S.rfind(sub [,start [,end]]) -& int<span style="color: #4
<span style="color: #5
Return the highest index in S where substring sub is found,<span style="color: #6
such that sub is contained within S[start:end].
Optional<span style="color: #7
arguments start and end are interpreted as in slice notation.<span style="color: #8
<span style="color: #9
Return -1 on failure.<span style="color: #0
"""<span style="color: #1
return 0<span style="color: #2 <span style="color: #3
def rindex(self, sub, start=None, end=None):
<span style="color: #4
"""<span style="color: #5
S.rindex(sub [,start [,end]]) -& int<span style="color: #6
<span style="color: #7
Like S.rfind() but raise ValueError when the substring is not found.<span style="color: #8
"""<span style="color: #9
return 0<span style="color: #0 <span style="color: #1
def rjust(self, width, fillchar=None):
<span style="color: #2
"""<span style="color: #3
S.rjust(width[, fillchar]) -& string<span style="color: #4
<span style="color: #5
Return S right-justified in a string of length width. Padding is<span style="color: #6
done using the specified fill character (default is a space)<span style="color: #7
"""<span style="color: #8
return ""<span style="color: #9 <span style="color: #0
def rpartition(self, sep):
<span style="color: #1
"""<span style="color: #2
S.rpartition(sep) -& (head, sep, tail)<span style="color: #3
<span style="color: #4
Search for the separator sep in S, starting at the end of S, and return<span style="color: #5
the part before it, the separator itself, and the part after it.
If the<span style="color: #6
separator is not found, return two empty strings and S.<span style="color: #7
"""<span style="color: #8
pass<span style="color: #9 <span style="color: #0
def rsplit(self, sep=None, maxsplit=None):
<span style="color: #1
"""<span style="color: #2
S.rsplit([sep [,maxsplit]]) -& list of strings<span style="color: #3
<span style="color: #4
Return a list of the words in the string S, using sep as the<span style="color: #5
delimiter string, starting at the end of the string and working<span style="color: #6
to the front.
If maxsplit is given, at most maxsplit splits are<span style="color: #7
done. If sep is not specified or is None, any whitespace string<span style="color: #8
is a separator.<span style="color: #9
"""<span style="color: #0
return []<span style="color: #1 <span style="color: #2
def rstrip(self, chars=None):
<span style="color: #3
"""<span style="color: #4
S.rstrip([chars]) -& string or unicode<span style="color: #5
<span style="color: #6
Return a copy of the string S with trailing whitespace removed.<span style="color: #7
If chars is given and not None, remove characters in chars instead.<span style="color: #8
If chars is unicode, S will be converted to unicode before stripping<span style="color: #9
"""<span style="color: #0
return ""<span style="color: #1 <span style="color: #2
def split(self, sep=None, maxsplit=None):
<span style="color: #3
""" 分割, maxsplit最多分割几次 """<span style="color: #4
"""<span style="color: #5
S.split([sep [,maxsplit]]) -& list of strings<span style="color: #6
<span style="color: #7
Return a list of the words in the string S, using sep as the<span style="color: #8
delimiter string.
If maxsplit is given, at most maxsplit<span style="color: #9
splits are done. If sep is not specified or is None, any<span style="color: #0
whitespace string is a separator and empty strings are removed<span style="color: #1
from the result.<span style="color: #2
"""<span style="color: #3
return []<span style="color: #4 <span style="color: #5
def splitlines(self, keepends=False):
<span style="color: #6
""" 根据换行分割 """<span style="color: #7
"""<span style="color: #8
S.splitlines(keepends=False) -& list of strings<span style="color: #9
<span style="color: #0
Return a list of the lines in S, breaking at line boundaries.<span style="color: #1
Line breaks are not included in the resulting list unless keepends<span style="color: #2
is given and true.<span style="color: #3
"""<span style="color: #4
return []<span style="color: #5 <span style="color: #6
def startswith(self, prefix, start=None, end=None):
<span style="color: #7
""" 是否起始 """<span style="color: #8
"""<span style="color: #9
S.startswith(prefix[, start[, end]]) -& bool<span style="color: #0
<span style="color: #1
Return True if S starts with the specified prefix, False otherwise.<span style="color: #2
With optional start, test S beginning at that position.<span style="color: #3
With optional end, stop comparing S at that position.<span style="color: #4
prefix can also be a tuple of strings to try.<span style="color: #5
"""<span style="color: #6
return False<span style="color: #7 <span style="color: #8
def strip(self, chars=None):
<span style="color: #9
""" 移除两段空白 """<span style="color: #0
"""<span style="color: #1
S.strip([chars]) -& string or unicode<span style="color: #2
<span style="color: #3
Return a copy of the string S with leading and trailing<span style="color: #4
whitespace removed.<span style="color: #5
If chars is given and not None, remove characters in chars instead.<span style="color: #6
If chars is unicode, S will be converted to unicode before stripping<span style="color: #7
"""<span style="color: #8
return ""<span style="color: #9 <span style="color: #0
def swapcase(self):
<span style="color: #1
""" 大写变小写,小写变大写 """<span style="color: #2
"""<span style="color: #3
S.swapcase() -& string<span style="color: #4
<span style="color: #5
Return a copy of the string S with uppercase characters<span style="color: #6
converted to lowercase and vice versa.<span style="color: #7
"""<span style="color: #8
return ""<span style="color: #9 <span style="color: #0
def title(self):
<span style="color: #1
"""<span style="color: #2
S.title() -& string<span style="color: #3
<span style="color: #4
Return a titlecased version of S, i.e. words start with uppercase<span style="color: #5
characters, all remaining cased characters have lowercase.<span style="color: #6
"""<span style="color: #7
return ""<span style="color: #8 <span style="color: #9
def translate(self, table, deletechars=None):
<span style="color: #0
"""<span style="color: #1
转换,需要先做一个对应表,最后一个表示删除字符集合<span style="color: #2
intab = "aeiou"<span style="color: #3
outtab = "<span style="color: #345"<span style="color: #4
trantab = maketrans(intab, outtab)<span style="color: #5
str = "this is string example....wow!!!"<span style="color: #6
print str.translate(trantab, 'xm')<span style="color: #7
"""<span style="color: #8 <span style="color: #9
"""<span style="color: #0
S.translate(table [,deletechars]) -& string<span style="color: #1
<span style="color: #2
Return a copy of the string S, where all characters occurring<span style="color: #3
in the optional argument deletechars are removed, and the<span style="color: #4
remaining characters have been mapped through the given<span style="color: #5
translation table, which must be a string of length 256 or None.<span style="color: #6
If the table argument is None, no translation is applied and<span style="color: #7
the operation simply removes the characters in deletechars.<span style="color: #8
"""<span style="color: #9
return ""<span style="color: #0 <span style="color: #1
def upper(self):
<span style="color: #2
"""<span style="color: #3
S.upper() -& string<span style="color: #4
<span style="color: #5
Return a copy of the string S converted to uppercase.<span style="color: #6
"""<span style="color: #7
return ""<span style="color: #8 <span style="color: #9
def zfill(self, width):
<span style="color: #0
"""方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""<span style="color: #1
"""<span style="color: #2
S.zfill(width) -& string<span style="color: #3
<span style="color: #4
Pad a numeric string S with zeros on the left, to fill a field<span style="color: #5
of the specified width.
The string S is never truncated.<span style="color: #6
"""<span style="color: #7
return ""<span style="color: #8 <span style="color: #9
def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown<span style="color: #0
pass<span style="color: #1 <span style="color: #2
def _formatter_parser(self, *args, **kwargs): # real signature unknown<span style="color: #3
pass<span style="color: #4 <span style="color: #5
def __add__(self, y):
<span style="color: #6
""" x.__add__(y) &==& x+y """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __contains__(self, y):
<span style="color: #0
""" x.__contains__(y) &==& y in x """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __eq__(self, y):
<span style="color: #4
""" x.__eq__(y) &==& x==y """<span style="color: #5
pass<span style="color: #6 <span style="color: #7
def __format__(self, format_spec):
<span style="color: #8
"""<span style="color: #9
S.__format__(format_spec) -& string<span style="color: #0
<span style="color: #1
Return a formatted version of S as described by format_spec.<span style="color: #2
"""<span style="color: #3
return ""<span style="color: #4 <span style="color: #5
def __getattribute__(self, name):
<span style="color: #6
""" x.__getattribute__('name') &==& x.name """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __getitem__(self, y):
<span style="color: #0
""" x.__getitem__(y) &==& x[y] """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __getnewargs__(self, *args, **kwargs): # real signature unknown<span style="color: #4
pass<span style="color: #5 <span style="color: #6
def __getslice__(self, i, j):
<span style="color: #7
"""<span style="color: #8
x.__getslice__(i, j) &==& x[i:j]<span style="color: #9
<span style="color: #0
Use of negative indices is not supported.<span style="color: #1
"""<span style="color: #2
pass<span style="color: #3 <span style="color: #4
def __ge__(self, y):
<span style="color: #5
""" x.__ge__(y) &==& x&=y """<span style="color: #6
pass<span style="color: #7 <span style="color: #8
def __gt__(self, y):
<span style="color: #9
""" x.__gt__(y) &==& x&y """<span style="color: #0
pass<span style="color: #1 <span style="color: #2
def __hash__(self):
<span style="color: #3
""" x.__hash__() &==& hash(x) """<span style="color: #4
pass<span style="color: #5 <span style="color: #6
def __init__(self, string=''): # known special case of str.__init__<span style="color: #7
"""<span style="color: #8
str(object='') -& string<span style="color: #9
<span style="color: #0
Return a nice string representation of the object.<span style="color: #1
If the argument is a string, the return value is the same object.<span style="color: #2
# (copied from class doc)<span style="color: #3
"""<span style="color: #4
pass<span style="color: #5 <span style="color: #6
def __len__(self):
<span style="color: #7
""" x.__len__() &==& len(x) """<span style="color: #8
pass<span style="color: #9 <span style="color: #0
def __le__(self, y):
<span style="color: #1
""" x.__le__(y) &==& x&=y """<span style="color: #2
pass<span style="color: #3 <span style="color: #4
def __lt__(self, y):
<span style="color: #5
""" x.__lt__(y) &==& x&y """<span style="color: #6
pass<span style="color: #7 <span style="color: #8
def __mod__(self, y):
<span style="color: #9
""" x.__mod__(y) &==& x%y """<span style="color: #0
pass<span style="color: #1 <span style="color: #2
def __mul__(self, n):
<span style="color: #3
""" x.__mul__(n) &==& x*n """<span style="color: #4
pass<span style="color: #5 <span style="color: #6
@staticmethod # known case of __new__<span style="color: #7
def __new__(S, *more):
<span style="color: #8
""" T.__new__(S, ...) -& a new object with type S, a subtype of T """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __ne__(self, y):
<span style="color: #2
""" x.__ne__(y) &==& x!=y """<span style="color: #3
pass<span style="color: #4 <span style="color: #5
def __repr__(self):
<span style="color: #6
""" x.__repr__() &==& repr(x) """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __rmod__(self, y):
<span style="color: #0
""" x.__rmod__(y) &==& y%x """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __rmul__(self, n):
<span style="color: #4
""" x.__rmul__(n) &==& n*x """<span style="color: #5
pass<span style="color: #6 <span style="color: #7
def __sizeof__(self):
<span style="color: #8
""" S.__sizeof__() -& size of S in memory, in bytes """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __str__(self):
<span style="color: #2
""" x.__str__() &==& str(x) """<span style="color: #3
pass<span style="color: #4 <span style="color: #5 strView Code 四、列表、元祖1.列表(list)列表常用操作:索引(index) 1 a=["a","b","c",1,2,3] 2 print(a.index("a"))#不加位置参数 3 输出: 4 <span style="color: # 5
6 a=["a","b","c","a",2,3] 7 print(a.index("a")) 8 print(a.index("a",1,5))#从索引1开始到5之间查找 9 输出:<span style="color: # <span style="color: #<span style="color: # 3View Code切片 1 &&& names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"] 2 &&& names[1:4]
#取下标1至下标4之间的数字,包括1,不包括4 3 ['Tenglan', 'Eric', 'Rain'] 4 &&& names[1:-1] #取下标1至-1的值,不包括-1 5 ['Tenglan', 'Eric', 'Rain', 'Tom'] 6 &&& names[0:3]
7 ['Alex', 'Tenglan', 'Eric'] 8 &&& names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样 9 ['Alex', 'Tenglan', 'Eric']<span style="color: # &&& names[3:] #如果想取最后一个,必须不能写-1,只能这么写<span style="color: # ['Rain', 'Tom', 'Amy'] <span style="color: # &&& names[3:-1] #这样-1就不会被包含了<span style="color: # ['Rain', 'Tom']<span style="color: # &&& names[-3:-1] #取最后两个效果同names[3:4]<span style="color: # ['Tom','Amy']<span style="color: # &&& names[0::2] #后面的2是代表,每隔一个元素,就取一个<span style="color: # ['Alex', 'Eric', 'Tom'] <span style="color: # &&& names[::2] #和上句效果一样<span style="color: # ['Alex', 'Eric', 'Tom']View Code追加(append)<span style="color: # a=["a","b","c","a",2,3]<span style="color: # a.append("WD")<span style="color: # print(a)<span style="color: # 输出:<span style="color: # ['a', 'b', 'c', 'a', 2, 3, 'WD']View Code删除(del,pop) 1 a=["a","b","c","d"] 2 del a[0] 3 print(a) 4 输出: 5 ['b', 'c', 'd'] 6
9 a=["a","b","c","d"]<span style="color: # a.pop()<span style="color: # print(a)#默认移除最后一个<span style="color: # 输出:<span style="color: # ['a', 'b', 'c']<span style="color: # #移除制定位置元素<span style="color: # a=["a","b","c","d"]<span style="color: # a.pop(2)#移除位置2的元素等价del a[2]<span style="color: # print(a)<span style="color: # 输出:<span style="color: # ['a', 'b', 'd']View Code插入(insert)<span style="color: # a=["a","b","c","a",2,3]<span style="color: # a.insert(0,"WD")#<span style="color: #代表索引,在0位置之前插入<span style="color: # print(a)<span style="color: # 输出:<span style="color: # ['WD', 'a', 'b', 'c', 'a', 2, 3]View Code扩展(extend)<span style="color: # a=["a","b","c"]<span style="color: # b=[1,2,3]<span style="color: # a.extend(b)<span style="color: # print(a)<span style="color: # 输出:<span style="color: # ['a', 'b', 'c', 1, 2, 3]View Code统计(count)<span style="color: # &&& names<span style="color: # ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '<span style="color: #', '<span style="color: #', '<span style="color: #']<span style="color: # &&& names.sort()<span style="color: # &&& names<span style="color: # ['<span style="color: #', '<span style="color: #', '<span style="color: #', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']<span style="color: # <span style="color: # &&& names.reverse() #反转<span style="color: # &&& names<span style="color: # ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '<span style="color: #', '<span style="color: #', '<span style="color: #']View Code排序(sort) 1 &&& names 2 ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3] 3 &&& names.sort() #排序 4 Traceback (most recent call last): 5
File "&stdin&", line 1, in &module& 6 TypeError: unorderable types: int() & str()
#<span style="color: #.0里不同数据类型不能放在一起排序了 7 &&& names[-3] = '<span style="color: #' 8 &&& names[-2] = '<span style="color: #' 9 &&& names[-1] = '<span style="color: #'<span style="color: # &&& names<span style="color: # ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '<span style="color: #', '<span style="color: #', '<span style="color: #']<span style="color: # &&& names.sort()<span style="color: # &&& names<span style="color: # ['<span style="color: #', '<span style="color: #', '<span style="color: #', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']<span style="color: # <span style="color: # &&& names.reverse() #反转<span style="color: # &&& names<span style="color: # ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '<span style="color: #', '<span style="color: #', '<span style="color: #']View Code循环(for)<span style="color: # a=["a","b","c","d"]<span style="color: # for i in a:<span style="color: #
print(i)<span style="color: # 输出:<span style="color: # a<span style="color: # b<span style="color: # c<span style="color: # dView Code包含(in)<span style="color: # a=["alex","wusir","wd"]<span style="color: # if "alex" in a:<span style="color: #
print("oh you are here!")<span style="color: # 输出:<span style="color: # oh you are here!View Code长度(len)<span style="color: # a=["a","b","c"]<span style="color: # print(len(a))<span style="color: # 结果:<span style="color: # 3View Code清空(clear)<span style="color: # a=["a","b","c"]<span style="color: # a.clear()<span style="color: # print(a)<span style="color: # 结果:<span style="color: # []View Code列表中含有的方法:
1 class list(object):
list() -& new empty list
list(iterable) -& new list initialized from iterable's items
def append(self, p_object): # re restored from __doc__
""" L.append(object) -- append object to end """
def count(self, value): # re restored from __doc__ 11
""" L.count(value) -& integer -- return number of occurrences of value """ 12
return 0 13
def extend(self, iterable): # re restored from __doc__ 15
""" L.extend(iterable) -- extend list by appending elements from the iterable """ 16
def index(self, value, start=None, stop=None): # re restored from __doc__ 19
L.index(value, [start, [stop]]) -& integer -- return first index of value. 21
Raises ValueError if the value is not present. 22
return 0 24
def insert(self, index, p_object): # re restored from __doc__ 26
""" L.insert(index, object) -- insert object before index """ 27
def pop(self, index=None): # re restored from __doc__ 30
L.pop([index]) -& item -- remove and return item at index (default last). 32
Raises IndexError if list is empty or index is out of range. 33
def remove(self, value): # re restored from __doc__ 37
L.remove(value) -- remove first occurrence of value. 39
Raises ValueError if the value is not present. 40
def reverse(self): # re restored from __doc__ 44
""" L.reverse() -- reverse *IN PLACE* """ 45
def sort(self, cmp=None, key=None, reverse=False): # re restored from __doc__ 48
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 50
cmp(x, y) -& -1, 0, 1 51
def __add__(self, y): # re restored from __doc__ 55
""" x.__add__(y) &==& x+y """ 56
def __contains__(self, y): # re restored from __doc__ 59
""" x.__contains__(y) &==& y in x """ 60
def __delitem__(self, y): # re restored from __doc__ 63
""" x.__delitem__(y) &==& del x[y] """ 64
def __delslice__(self, i, j): # re restored from __doc__ 67
x.__delslice__(i, j) &==& del x[i:j] 69
Use of negative indices is not supported. 71
def __eq__(self, y): # re restored from __doc__ 75
""" x.__eq__(y) &==& x==y """ 76
def __getattribute__(self, name): # re restored from __doc__ 79
""" x.__getattribute__('name') &==& x.name """ 80
def __getitem__(self, y): # re restored from __doc__ 83
""" x.__getitem__(y) &==& x[y] """ 84
def __getslice__(self, i, j): # re restored from __doc__ 87
x.__getslice__(i, j) &==& x[i:j] 89
Use of negative indices is not supported. 91
def __ge__(self, y): # re restored from __doc__ 95
""" x.__ge__(y) &==& x&=y """ 96
def __gt__(self, y): # re restored from __doc__ 99
""" x.__gt__(y) &==& x&y """<span style="color: #0
pass<span style="color: #1 <span style="color: #2
def __iadd__(self, y): # re restored from __doc__<span style="color: #3
""" x.__iadd__(y) &==& x+=y """<span style="color: #4
pass<span style="color: #5 <span style="color: #6
def __imul__(self, y): # re restored from __doc__<span style="color: #7
""" x.__imul__(y) &==& x*=y """<span style="color: #8
pass<span style="color: #9 <span style="color: #0
def __init__(self, seq=()): # known special case of list.__init__<span style="color: #1
"""<span style="color: #2
list() -& new empty list<span style="color: #3
list(iterable) -& new list initialized from iterable's items<span style="color: #4
# (copied from class doc)<span style="color: #5
"""<span style="color: #6
pass<span style="color: #7 <span style="color: #8
def __iter__(self): # re restored from __doc__<span style="color: #9
""" x.__iter__() &==& iter(x) """<span style="color: #0
pass<span style="color: #1 <span style="color: #2
def __len__(self): # re restored from __doc__<span style="color: #3
""" x.__len__() &==& len(x) """<span style="color: #4
pass<span style="color: #5 <span style="color: #6
def __le__(self, y): # re restored from __doc__<span style="color: #7
""" x.__le__(y) &==& x&=y """<span style="color: #8
pass<span style="color: #9 <span style="color: #0
def __lt__(self, y): # re restored from __doc__<span style="color: #1
""" x.__lt__(y) &==& x&y """<span style="color: #2
pass<span style="color: #3 <span style="color: #4
def __mul__(self, n): # re restored from __doc__<span style="color: #5
""" x.__mul__(n) &==& x*n """<span style="color: #6
pass<span style="color: #7 <span style="color: #8
@staticmethod # known case of __new__<span style="color: #9
def __new__(S, *more): # re restored from __doc__<span style="color: #0
""" T.__new__(S, ...) -& a new object with type S, a subtype of T """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __ne__(self, y): # re restored from __doc__<span style="color: #4
""" x.__ne__(y) &==& x!=y """<span style="color: #5
pass<span style="color: #6 <span style="color: #7
def __repr__(self): # re restored from __doc__<span style="color: #8
""" x.__repr__() &==& repr(x) """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __reversed__(self): # re restored from __doc__<span style="color: #2
""" L.__reversed__() -- return a reverse iterator over the list """<span style="color: #3
pass<span style="color: #4 <span style="color: #5
def __rmul__(self, n): # re restored from __doc__<span style="color: #6
""" x.__rmul__(n) &==& n*x """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __setitem__(self, i, y): # re restored from __doc__<span style="color: #0
""" x.__setitem__(i, y) &==& x[i]=y """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __setslice__(self, i, j, y): # re restored from __doc__<span style="color: #4
"""<span style="color: #5
x.__setslice__(i, j, y) &==& x[i:j]=y<span style="color: #6
<span style="color: #7
of negative indices is not supported.<span style="color: #8
"""<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __sizeof__(self): # re restored from __doc__<span style="color: #2
""" L.__sizeof__() -- size of L in memory, in bytes """<span style="color: #3
pass<span style="color: #4 <span style="color: #5
__hash__ = None<span style="color: #6 <span style="color: #7 listView Code2.元祖(tuple)元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表元祖操作: 索引切片循环长度包含 五、字典3.字典字典的特性:dict是无序的key必须是唯一的,天生去重字典操作:索引(key)<span style="color: # a={"name":"WD","age":"<span style="color: #","job":"IT"}<span style="color: # print(a["name"])<span style="color: # 输出:<span style="color: # WDView Code增加 <span style="color: # a={"name":"WD","age":"<span style="color: #","job":"IT"}<span style="color: # a["city"]="chengdu"<span style="color: # print(a)<span style="color: # 输出:<span style="color: # {'city': 'chengdu', 'age': '<span style="color: #', 'job': 'IT', 'name': 'WD'}View Code修改<span style="color: # a={"name":"WD","age":"<span style="color: #","job":"IT"}<span style="color: # a["name"]="alex"<span style="color: # print(a)<span style="color: # 输出:<span style="color: # {'name': 'alex', 'job': 'IT', 'age': '<span style="color: #'}View Code删除(del、pop) 1 &&& info 2 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'} 3 &&& info.pop("stu1101") #标准删除姿势 4 '武藤兰' 5 &&& info 6 {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} 7 &&& del info['stu1103'] #换个姿势删除 8 &&& info 9 {'stu1102': 'LongZe Luola'}<span style="color: # &&& <span style="color: # &&& <span style="color: # &&& <span style="color: # &&& info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}<span style="color: # &&& info<span style="color: # {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除<span style="color: # &&& info.popitem()<span style="color: # ('stu1102', 'LongZe Luola')<span style="color: # &&& info<span style="color: # {'stu1103': 'XiaoZe Maliya'}View Code查找(get) <span style="color: # &&& msg={"name":"WD","age":22,"job":"IT"}<span style="color: # &&& msg["name"]#如果获取索引不存在会报错<span style="color: # 'WD'<span style="color: # &&& "name" in msg#标准姿势<span style="color: # True<span style="color: # &&& msg.get("name")#get获取不到元素返回None不会报错<span style="color: # 'WD'View Code键、值、键值对<span style="color: # msg={"name":"WD","age":22,"job":"IT"}<span style="color: # print(msg.keys())#打印所有的key<span style="color: # print(msg.values())#打印所有的值<span style="color: # print(msg.items())#打印键值对<span style="color: # 结果:<span style="color: # dict_keys(['job', 'age', 'name'])<span style="color: # dict_values(['IT', 22, 'WD'])<span style="color: # dict_items([('job', 'IT'), ('age', 22), ('name', 'WD')])View Code循环(for、enumerate) 1 for 2 #方法1 3 for key in info: 4
print(key,info[key]) 5
6 #方法2 7 for k,v in info.items(): #会先把dict转成list,数据里大不要用 8
print(k,v) 9 <span style="color: # enumerate#自动为对象添加序号<span style="color: # a={"name":"WD","age":22,"job":"IT"}<span style="color: # for i,k in enumerate(a.keys()):#此处有坑,a.keys()每次顺序可能不一样<span style="color: #
print(i,a[k])<span style="color: # 结果:<span style="color: # 0 22<span style="color: # 1 IT<span style="color: # 2 WDView Code长度(len)<span style="color: # msg={"name":"WD","age":22,"job":"IT"}<span style="color: # print(len(msg))<span style="color: # 结果:<span style="color: # 3View Code其他操作(update、setdefault) 1 update#字典更新,若key相同覆盖,key不存在则增加
2 a={"name":"WD","age":22,"job":"IT"} 3 b={"name":"alex","age":33,"city":"beijing"} 4 a.update(b) 5 print(a) 6 结果: 7 {'name': 'alex', 'age': 33, 'city': 'beijing', 'job': 'IT'} 8
9 setdefault#为字典设置默认值,若字典中没有该值,采用默认。<span style="color: # a={"name":"WD","age":22,"job":"IT"}<span style="color: # a.setdefault("name","alex")<span style="color: # print(a)<span style="color: # 结果:<span style="color: # {'name': 'WD', 'job': 'IT', 'age': 22}#为采用默认值View Code字典中含有的方法:
1 class dict(object):
dict() -& new empty dictionary
dict(mapping) -& new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -& new dictionary initialized as if via:
for k, v in iterable:
d[k] = v 10
dict(**kwargs) -& new dictionary initialized with the name=value pairs 11
in the keyword argument list.
For example:
dict(one=1, two=2) 12
def clear(self): # re restored from __doc__ 15
""" 清除内容 """ 16
""" D.clear() -& None.
Remove all items from D. """ 17
def copy(self): # re restored from __doc__ 20
""" 浅拷贝 """ 21
""" D.copy() -& a shallow copy of D """ 22
@staticmethod # known case 25
def fromkeys(S, v=None): # re restored from __doc__ 26
dict.fromkeys(S[,v]) -& New dict with keys from S and values equal to v. 28
v defaults to None. 29
def get(self, k, d=None): # re restored from __doc__ 33
""" 根据key获取值,d是默认值 """ 34
""" D.get(k[,d]) -& D[k] if k in D, else d.
d defaults to None. """ 35
def has_key(self, k): # re restored from __doc__ 38
""" 是否有key """ 39
""" D.has_key(k) -& True if D has a key k, else False """ 40
return False 41
def items(self): # re restored from __doc__ 43
""" 所有项的列表形式 """ 44
""" D.items() -& list of D's (key, value) pairs, as 2-tuples """ 45
return [] 46
def iteritems(self): # re restored from __doc__ 48
""" 项可迭代 """ 49
""" D.iteritems() -& an iterator over the (key, value) items of D """ 50
def iterkeys(self): # re restored from __doc__ 53
""" key可迭代 """ 54
""" D.iterkeys() -& an iterator over the keys of D """ 55
def itervalues(self): # re restored from __doc__ 58
""" value可迭代 """ 59
""" D.itervalues() -& an iterator over the values of D """ 60
def keys(self): # re restored from __doc__ 63
""" 所有的key列表 """ 64
""" D.keys() -& list of D's keys """ 65
return [] 66
def pop(self, k, d=None): # re restored from __doc__ 68
""" 获取并在字典中移除 """ 69
D.pop(k[,d]) -& v, remove specified key and return the corresponding value. 71
If key is not found, d is returned if given, otherwise KeyError is raised 72
def popitem(self): # re restored from __doc__ 76
""" 获取并在字典中移除 """ 77
D.popitem() -& (k, v), remove and return some (key, value) pair as a 79
2- but raise KeyError if D is empty. 80
def setdefault(self, k, d=None): # re restored from __doc__ 84
""" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ 85
""" D.setdefault(k[,d]) -& D.get(k,d), also set D[k]=d if k not in D """ 86
def update(self, E=None, **F): # known special case of dict.update 89
""" 更新 90
{'name':'alex', 'age': 18000} 91
[('name','sbsbsb'),] 92
D.update([E, ]**F) -& None.
Update D from dict/iterable E and F. 95
If E present and has a .keys() method, does:
for k in E: D[k] = E[k] 96
If E present and lacks .keys() method, does:
for (k, v) in E: D[k] = v 97
In either case, this is followed by: for k in F: D[k] = F[k] 98
pass<span style="color: #0 <span style="color: #1
def values(self): # re restored from __doc__<span style="color: #2
""" 所有的值 """<span style="color: #3
""" D.values() -& list of D's values """<span style="color: #4
return []<span style="color: #5 <span style="color: #6
def viewitems(self): # re restored from __doc__<span style="color: #7
""" 所有项,只是将内容保存至view对象中 """<span style="color: #8
""" D.viewitems() -& a set-like object providing a view on D's items """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def viewkeys(self): # re restored from __doc__<span style="color: #2
""" D.viewkeys() -& a set-like object providing a view on D's keys """<span style="color: #3
pass<span style="color: #4 <span style="color: #5
def viewvalues(self): # re restored from __doc__<span style="color: #6
""" D.viewvalues() -& an object providing a view on D's values """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __cmp__(self, y): # re restored from __doc__<span style="color: #0
""" x.__cmp__(y) &==& cmp(x,y) """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __contains__(self, k): # re restored from __doc__<span style="color: #4
""" D.__contains__(k) -& True if D has a key k, else False """<span style="color: #5
return False<span style="color: #6 <span style="color: #7
def __delitem__(self, y): # re restored from __doc__<span style="color: #8
""" x.__delitem__(y) &==& del x[y] """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __eq__(self, y): # re restored from __doc__<span style="color: #2
""" x.__eq__(y) &==& x==y """<span style="color: #3
pass<span style="color: #4 <span style="color: #5
def __getattribute__(self, name): # re restored from __doc__<span style="color: #6
""" x.__getattribute__('name') &==& x.name """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __getitem__(self, y): # re restored from __doc__<span style="color: #0
""" x.__getitem__(y) &==& x[y] """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
def __ge__(self, y): # re restored from __doc__<span style="color: #4
""" x.__ge__(y) &==& x&=y """<span style="color: #5
pass<span style="color: #6 <span style="color: #7
def __gt__(self, y): # re restored from __doc__<span style="color: #8
""" x.__gt__(y) &==& x&y """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __init__(self, seq=None, **kwargs): # known special case of dict.__init__<span style="color: #2
"""<span style="color: #3
dict() -& new empty dictionary<span style="color: #4
dict(mapping) -& new dictionary initialized from a mapping object's<span style="color: #5
(key, value) pairs<span style="color: #6
dict(iterable) -& new dictionary initialized as if via:<span style="color: #7
d = {}<span style="color: #8
for k, v in iterable:<span style="color: #9
d[k] = v<span style="color: #0
dict(**kwargs) -& new dictionary initialized with the name=value pairs<span style="color: #1
in the keyword argument list.
For example:
dict(one=1, two=2)<span style="color: #2
# (copied from class doc)<span style="color: #3
"""<span style="color: #4
pass<span style="color: #5 <span style="color: #6
def __iter__(self): # re restored from __doc__<span style="color: #7
""" x.__iter__() &==& iter(x) """<span style="color: #8
pass<span style="color: #9 <span style="color: #0
def __len__(self): # re restored from __doc__<span style="color: #1
""" x.__len__() &==& len(x) """<span style="color: #2
pass<span style="color: #3 <span style="color: #4
def __le__(self, y): # re restored from __doc__<span style="color: #5
""" x.__le__(y) &==& x&=y """<span style="color: #6
pass<span style="color: #7 <span style="color: #8
def __lt__(self, y): # re restored from __doc__<span style="color: #9
""" x.__lt__(y) &==& x&y """<span style="color: #0
pass<span style="color: #1 <span style="color: #2
@staticmethod # known case of __new__<span style="color: #3
def __new__(S, *more): # re restored from __doc__<span style="color: #4
""" T.__new__(S, ...) -& a new object with type S, a subtype of T """<span style="color: #5
pass<span style="color: #6 <span style="color: #7
def __ne__(self, y): # re restored from __doc__<span style="color: #8
""" x.__ne__(y) &==& x!=y """<span style="color: #9
pass<span style="color: #0 <span style="color: #1
def __repr__(self): # re restored from __doc__<span style="color: #2
""" x.__repr__() &==& repr(x) """<span style="color: #3
pass<span style="color: #4 <span style="color: #5
def __setitem__(self, i, y): # re restored from __doc__<span style="color: #6
""" x.__setitem__(i, y) &==& x[i]=y """<span style="color: #7
pass<span style="color: #8 <span style="color: #9
def __sizeof__(self): # re restored from __doc__<span style="color: #0
""" D.__sizeof__() -& size of D in memory, in bytes """<span style="color: #1
pass<span style="color: #2 <span style="color: #3
__hash__ = None<span style="color: #4 <span style="color: #5 dictView Code 六、集合集合是一个无序的,不重复的数据组合,特性:去重,把一个列表变成集合,就自动去重了关系测试,测试两组数据之前的交集、差集、并集等关系常用操作: 1 s = set([3,5,9,10])
#创建一个数值集合
3 t = set("Hello")
#创建一个唯一字符的集合
6 a = t | s
# t 和 s的并集
8 b = t & s
# t 和 s的交集
<span style="color: # c = t – s
# 求差集(项在t中,但不在s中)
<span style="color: #
<span style="color: # d = t ^ s
# 对称差集(项在t或s中,但不会同时出现在二者中)
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: # 基本操作:
<span style="color: #
<span style="color: # t.add('x')
# 添加一项
<span style="color: #
<span style="color: # s.update([10,37,42])
# 在s中添加多项
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: # 使用remove()可以删除一项:
<span style="color: #
<span style="color: # t.remove('H')
<span style="color: #
<span style="color: #
<span style="color: # len(s)
<span style="color: # set 的长度
<span style="color: #
<span style="color: # x in s
<span style="color: # 测试 x 是否是 s 的成员
<span style="color: #
<span style="color: # x not in s
<span style="color: # 测试 x 是否不是 s 的成员
<span style="color: #
<span style="color: # s.issubset(t)
<span style="color: # s &= t
<span style="color: # 测试是否 s 中的每一个元素都在 t 中
<span style="color: #
<span style="color: # s.issuperset(t)
<span style="color: # s &= t
<span style="color: # 测试是否 t 中的每一个元素都在 s 中
<span style="color: #
<span style="color: # s.union(t)
<span style="color: # s | t
<span style="color: # 返回一个新的 set 包含 s 和 t 中的每一个元素
<span style="color: #
<span style="color: # s.intersection(t)
<span style="color: # s & t
<span style="color: # 返回一个新的 set 包含 s 和 t 中的公共元素
<span style="color: #
<span style="color: # s.difference(t)
<span style="color: # s - t
<span style="color: # 返回一个新的 set 包含 s 中有但是 t 中没有的元素
<span style="color: #
<span style="color: # s.symmetric_difference(t)
<span style="color: # s ^ t
<span style="color: # 返回一个新的 set 包含 s 和 t 中不重复的元素
<span style="color: #
<span style="color: # s.copy()
<span style="color: # 返回 set “s”的一个浅复制View Code 七、练习题1.三级菜单需求:1. 运行程序输出第一级菜单2. 选择一级菜单某项,输出二级菜单,同理输出三级菜单3. 菜单数据保存在文件中代码: 1 #/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #Author:W-D 4 flag=True 5 menu_list=[]#保存文件中每条菜单信息 6 menu_key=[]#保存一级菜单中的key 7 menu = {}#保存需要用的菜单 8 with open ("menu.txt","r",encoding="utf-8") as f: 9
for line in f:<span style="color: #
msg=line.strip().split(":")#将文件中的每行按:分割成列表<span style="color: #
if msg[0] not in menu_key:<span style="color: #
menu_key.append(msg[0])#将一级菜单中的key追加到列表中<span style="color: #
menu_list.append(msg)#将文件中每条信息追加到列表中,用于后续处理<span style="color: #
for city in menu_key:#外层循环城市<span style="color: #
menu3 = {}#这个是个坑!!每次循环完结果出来以后,需要将第是三级菜单清空,会影响下一个城市所生成的字典<span style="color: #
for each in menu_list:#<span style="color: #
if city==each[0]:<span style="color: #
key,value=each[1].split(" ")[0],each[1].split(" ")[1:]#生成三级菜单的key和value<span style="color: #
menu3[key]=value#同上<span style="color: #
menu[city]=menu3#同上<span style="color: # while flag:<span style="color: #
for i in menu:<span style="color: #
print(i)<span style="color: #
choice=input("请输入您的选择(q退出):")<span style="color: #
if choice in menu:<span style="color: #
while flag:<span style="color: #
for i1 in menu[choice]:<span style="color: #
print(i1)<span style="color: #
choice1 = input("请输入您的选择(q退出,b返回):")<span style="color: #
if choice1 in menu[choice]:<span style="color: #
while flag:<span style="color: #
for i2 in menu[choice][choice1]:<span style="color: #
print(i2)<span style="color: #
choice2 = input("请输入您的选择(q退出,b返回):")<span style="color: #
if choice2 == 'q':<span style="color: #
flag = False<span style="color: #
break<span style="color: #
elif choice2 == 'b':<span style="color: #
break<span style="color: #
else:<span style="color: #
print("已经到底了!")<span style="color: #
elif choice1=='q':<span style="color: #
flag=False<span style="color: #
break<span style="color: #
elif choice1=='b':<span style="color: #
break<span style="color: #
if choice=='q':<span style="color: #
flag=False<span style="color: #
break三级菜单之常用方法菜单文件:<span style="color: # 北京市:昌平 A公司 B公司 C公司,<span style="color: # 北京市:回龙观 E公司 F公司 G公司<span style="color: # 上海市:浦东 H公司 I公司 J公司<span style="color: # 上海市:虹桥 U公司 V公司 W公司<span style="color: # 成都市:金牛区 O公司 P公司 Q公司<span style="color: # 成都市:高新区 X公司 Y公司 Z公司menu.txt大王的无敌方法: 1 menu = { 2
'北京':{ 3
'海淀':{ 4
'五道口':{ 5
'soho':{}, 6
'网易':{}, 7
'google':{} 8
'中关村':{<span style="color: #
'爱奇艺':{},<span style="color: #
'汽车之家':{},<span style="color: #
'youku':{},<span style="color: #
},<span style="color: #
'上地':{<span style="color: #
'百度':{},<span style="color: #
},<span style="color: #
},<span style="color: #
'昌平':{<span style="color: #
'沙河':{<span style="color: #
'老男孩':{},<span style="color: #
'北航':{},<span style="color: #
},<span style="color: #
'天通苑':{},<span style="color: #
'回龙观':{},<span style="color: #
},<span style="color: #
'朝阳':{},<span style="color: #
'东城':{},<span style="color: #
},<span style="color: #
'上海':{<span style="color: #
'闵行':{<span style="color: #
"人民广场":{<span style="color: #
'炸鸡店':{}<span style="color: #
}<span style="color: #
},<span style="color: #
'闸北':{<span style="color: #
'火车战':{<span style="color: #
'携程':{}<span style="color: #
}<span style="color: #
},<span style="color: #
'浦东':{},<span style="color: #
},<span style="color: #
'山东':{},<span style="color: # }<span style="color: # <span style="color: # <span style="color: # exit_flag = False<span style="color: # current_layer = menu<span style="color: # <span style="color: # layers = [menu]<span style="color: # <span style="color: # while not
exit_flag:<span style="color: #
for k in current_layer:<span style="color: #
print(k)<span style="color: #
choice = input("&&:").strip()<span style="color: #
if choice == "b":<span style="color: #
current_layer = layers[-1]<span style="color: #
#print("change to laster", current_layer)<span style="color: #
layers.pop()<span style="color: #
elif choice not
in current_layer:continue<span style="color: #
else:<span style="color: #
layers.append(current_layer)<span style="color: #
current_layer = current_layer[choice]三级菜单之文艺方法
免责声明:本站部分内容、图片、文字、视频等来自于互联网,仅供大家学习与交流。相关内容如涉嫌侵犯您的知识产权或其他合法权益,请向本站发送有效通知,我们会及时处理。反馈邮箱&&&&。
学生服务号
在线咨询,奖学金返现,名师点评,等你来互动}

我要回帖

更多关于 gre argument 错误 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信