@maorongrong
2017-03-28T14:17:20.000000Z
字数 9192
阅读 610
for-github
摘要: 只有刷题,你才会知道自己有多渣。。。
In [1]: a=[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
In [2]: print map(list,zip(*a))
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
来个基础版
# 笨办法
b=[]
for i in range(len(a[0])):
row=[]
for j in range(len(a)):
row.append(a[j][i])
b.append(row)
print(b)
# 以上写成一句
print([[row[i] for row in a] for i in range(len(a[0]))])
# 用函数zip更直观
list(list(i) for i in zip(*a))
mylist = [1,2,2,2,2,3,3,3,4,4,4,4]
myset = set(mylist) #myset是另外一个列表,里面的内容是mylist里面的无重复 项
for item in myset:
print("the %d has found %d" %(item,mylist.count(item)))
List=[1,2,2,2,2,3,3,3,4,4,4,4]
a = {}
for i in List:
if List.count(i)>1:
a[i] = List.count(i)
print (a)
>>> from collections import Counter
>>> Counter([1,2,2,2,2,3,3,3,4,4,4,4])
Counter({1: 5, 2: 3, 3: 2})
sys.stdin.readline( )会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的,
但是raw_input( )获取输入时返回的结果是不包含末尾的换行符'\n'的.因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数去掉(sys.stdin.readline( ).strip('\n')),这样处理一下就行了
itertools.groupby(iterable[, key]): the iterable needs to already be sorted on the same key function.
In [1]: from itertools import groupby
In [2]: xs = ['b', 'b', 'b', 'a', 'a', 'b', 'b', 'b', 'b', 'a', 'a', 'b', 'a', 'a', 'b', 'a']
In [3]: print max(len(list(g)) for k, g in groupby(xs) if k=='b')
4
https://my.oschina.net/zyzzy/blog/115096
map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended withNoneitems. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
>>> def add100(x):
... return x+100
...
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
>>> def abc(a, b, c):
... return a*10000 + b*100 + c
...
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(abc,list1,list2,list3)
[114477, 225588, 336699]
看到并行的效果了吧!在每个list中,取出了下标相同的元素,执行了abc()。
>>> list1 = [11,22,33]
>>> map(None,list1)
[11, 22, 33]
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(None,list1,list2,list3)
[(11, 44, 77), (22, 55, 88), (33, 66, 99)]
对于**多个迭代参数**iterables,None
function作用类似与map()
,即按列组成tuple,以list返回所有列tuple组合。
http://www.cnblogs.com/frydsh/archive/2012/07/10/2585370.html
zip([iterable, ...])
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to t**he length of the shortest argument sequence**. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).
zip() in conjunction with the * operator can be used to unzip a list
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
u = zip(*xyz)
print u
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
一般认为这是一个unzip的过程,它的运行机制是这样的:
在运行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
那么,zip(*xyz) 等价于 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))
所以,运行结果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
x = [1, 2, 3]
r = zip(* [x] * 3)
print r
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
它的运行机制是这样的:
[x]生成一个列表的列表,它只有一个元素x
[x] * 3生成一个列表的列表,它有3个元素,[x, x, x]
zip(* [x] * 3)的意思就明确了,zip(x, x, x)
file.close()
Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.
As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically close f when the with block is exited:
from __future__ import with_statement # This isn't required in Python 2.6
with open("hello.txt") as f:
for line in f:
print line,
In older versions of Python, you would have needed to do this to get the same effect:
f = open("hello.txt")
try:
for line in f:
print line,
finally:
f.close()
file.read([size])
Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given.Note This function is simply a wrapper for the underlying fread() C function, and will behave the same in corner cases, such as whether the EOF value is cached.
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately.
Note Unlike stdio‘s fgets(), the returned string contains null characters ('\0') if they occurred in the input.
file.readline()读取的line包括后面的换行符'\n'
,因此一般使用file.readline().strip()
或者sys.stdin.readline.strip()
file.readlines([sizehint])
Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.
返回记录各行lines的list, 注意,每一行line是调用readline()
方法读取的,因此包含换行符'\n'
,需要使用strip()
去掉。
Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:
>>>
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]
What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list.
The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.
>>>
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]
List and bytearray objects support additional operations that allow in-place modification of the object. Other mutable sequence types (when added to the language) should also support these operations. Strings and tuples are immutable sequence types: such objects cannot be modified once created. The following operations are defined on mutable sequence types (where x is an arbitrary object):
Operation | Result | Notes |
---|---|---|
s[i] = x | item i of s is replaced by x | |
s[i:j] = t | slice of s from i to j is replaced by the contents of the iterable t | |
del s[i:j] | same as s[i:j] = [] | |
s[i:j:k] = t | the elements of s[i:j:k] are replaced by those of t | (1) |
del s[i:j:k] | removes the elements of s[i:j:k] from the list | |
s.append(x) | same as s[len(s):len(s)] = [x] | (2) |
s.extend(t) or s += t | for the most part the same as s[len(s):len(s)] = t | (3) |
s *= n | updates s with its contents repeated n times | (11) |
s.count(x) | return number of i‘s for which s[i] == x | |
s.index(x[, i[, j]]) | return smallest k such that s[k] == x and i <= k < j | (4) |
s.insert(i, x) | same as s[i:i] = [x] | (5) |
s.pop([i]) | same as x = s[i]; del s[i]; return x | (6) |
s.remove(x) | same as del s[s.index(x)] | (4) |
s.reverse() | reverses the items of s in place | (7) |
s.sort([cmp[, key[, reverse]]]) | sort the items of s in place | (7)(8)(9)(10) |
The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.
A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
There are currently two built-in set types,
set
andfrozenset
. The set type is mutable — the contents can be changed using methods like add() and remove(). Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.As of Python 2.7, non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: {'jack', 'sjoerd'}, in addition to the set constructor.
Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned.