在python中对.pop和.split感到困惑

时间:2017-02-08 15:04:49

标签: python

我对python很新,我很难理解.pop和.split会做什么,以及他们将会使用什么样的情况。

2 个答案:

答案 0 :(得分:1)

bruno@fritzbee:~$ python

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help(list.pop)
Help on method_descriptor:

pop(...)
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.
(END)
    >>> l = list("abcd")
>>> print l
['a', 'b', 'c', 'd']
>>> x = l.pop()
>>> print x
d
>>> print l
['a', 'b', 'c']
>>> y = l.pop(0)
>>> print y
a
>>> print l
['b', 'c']
>>> 
>>> help(str.split)
Help on method_descriptor:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are removed
    from the result.

>>> sentence = "this is an example"
>>> words = sentence.split()
>>> print words
['this', 'is', 'an', 'example']
>>> row = "a,b,c,d"
>>> row.split(',')
['a', 'b', 'c', 'd']
>>> querystring = "a=1&foo=bar&baaz=42"
>>> args = dict(p.split("=") for p in querystring.split("&"))
>>> print args
{'a': '1', 'baaz': '42', 'foo': 'bar'}
>>> 

答案 1 :(得分:0)

.pop会忽略列表中的项目。

lst=['a','b','c','d']
# to omit 'b' from the list we use .pop
lst.pop(1)
print(lst)
# lst=['a','c','d']
但是,.split函数会将字符串拆分为包含字符串项的列表。

a="hello world"
a.split()
['hello', 'world']