月度归档:2014年08月

python zip

zip就是把2个数组糅在一起

python3

>>> temp=[[1, 2, [3, 4], [5, 6], 7], [21, 22, [23, 24], [25, 26], 27], [31, 32, [3, 4], [35, 36], 37], [41, 42, [43, 44], [45, 46], 47], [51, 52, [23, 24], [55, 56], 57]]

>>> list(zip(*temp[::1]))[2]
([3, 4], [23, 24], [3, 4], [43, 44], [23, 24])

>>> help(zip)
Help on class zip in module builtins:

class zip(object)
| zip(iter1 [,iter2 […]]) –> zip object
|
| Return a zip object whose .__next__() method returns a tuple where
| the i-th element comes from the i-th iterable argument. The .__next__()
| method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises StopIteration.
|
| Methods defined here:
|
| __getattribute__(…)
| x.__getattribute__(‘name’) <==> x.name
|
| __iter__(…)
| x.__iter__() <==> iter(x)
|
| __next__(…)
| x.__next__() <==> next(x)
|
| __reduce__(…)
| Return state information for pickling.
|
| ———————————————————————-
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, …) -> a new object with type S, a subtype of T

 

python2

>>> temp=[[1, 2, [3, 4], [5, 6], 7], [21, 22, [23, 24], [25, 26], 27], [31, 32, [3, 4], [35, 36], 37], [41, 42, [43, 44], [45, 46], 47], [51, 52, [23, 24], [55, 56], 57]]
>>> xx=list(zip(*temp[::1])[2])
>>> xx
[[3, 4], [23, 24], [3, 4], [43, 44], [23, 24]]
>>> help(zip)
Help on built-in function zip in module __builtin__:

zip(…)
zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

 

注意,python2里,

list(zip(*temp[::1]))[2]

list(zip(*temp[::1])[2]) 都是可以的

而python3里,则只能用:list(zip(*temp[::1]))[2]

python 无间隔print输出

很久以前就碰到这个问题,解决的方法是在print之前,对字符串进行处理,比如用mako写好。现在终于知道print是原本支持无间隔输出的了。

>>> help(print)
Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’n’, file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

 

例子:

>>> numStars=5
>>> for i in range (1,numStars+1):
print(‘*’,sep=”” ,end=””)
*****
>>>