欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python Learning: 03

程序员文章站 2022-04-28 13:02:52
An inch is worth a pound of gold, an inch of gold is hard to buy an inch of time. Slice When the scale of data is so large that we have to pick a shor ......

    an inch is worth a pound of gold, an inch of gold is hard to buy an inch of time.

  • slice

    when the scale of data is so large that we have to pick a short of the content, the best way is to use slice.

    • forward slice
>>>l=range(1,101)
>>>l[1:]              #until the end
>>>l[:101]          #from the first
>>>l[1:100]
>>>l[1:101:2]     #pick one in two
    • reverse slice
>>>l=range(1,101)
>>>l[-1:]  
>>>l[:-1]
>>>l[-5:-1]
>>>l[-46::5]
  • iteration

    in python, iterations are done with "for ... in ...". 'for' loop in python can be used not only on lists and tuples, but alse on any other iterable objects. therefore, the iterative operation is for a collection, whether the collection is ordered or unordered, we can always use the loop to extract each element of the collection in turn. the collection is a data structure containing a set of elements, and we have learnt list, tuple, set, dict, str, unicode.

    • index iteration: using enumerate() to get the tuple of index and name and using zip() to conbine two lists into one
for index, name in enumerate(l):
    print index, '-', name
>>> zip([10, 20, 30], ['a', 'b', 'c'])
[(10, 'a'), (20, 'b'), (30, 'c')]
    • the value of dict: values()  and  itervalues()
    • the key-value of dict: items()  and iteritems()