python基本用法

匿名 (未验证) 提交于 2019-12-02 22:51:30

PYTHONPATH

PYTHONPATH是python moudle的搜索路径.即import xxx会从$PYTHONPATH寻找xxx.

#coding=utf-8

import a_module
print(a_module.__file__)

map(function, iterable, ...)

参数
function -- 函数
iterable -- 一个或多个序列

返回值
Python 2.x 返回列表。
Python 3.x 返回迭代器。

>>>def square(x) :            # 计算平方数 ...     return x ** 2 ...  >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方 [1, 4, 9, 16, 25] >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数 [1, 4, 9, 16, 25]   # 提供了两个列表,对相同位置的列表数据进行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19]

What is :: (double colon) in Python when subscripting sequences?

https://stackoverflow.com/questions/3453085/what-is-double-colon-in-python-when-subscripting-sequences

It returns every item on a position that is a multiple of 3. Since 3*0=0, it returns also the item on position 0. For instance: range(10)[::3] outputs [0, 3, 6, 9]

每隔xxx个元素做切片

transpose

比如img是h*w*c维(h是第0维,w是第1维,c是第2维)的矩阵. 在经过transpose((2,0,1))后变为c*h*w的矩阵

enumerate

>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1))       # 下标从 1 开始 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

range(start, stop[, step])

  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
 >>>range(10)        # 从 0 开始到 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11)     # 从 1 开始到 11 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> range(0, 30, 5)  # 步长为 5 [0, 5, 10, 15, 20, 25] >>> range(0, 10, 3)  # 步长为 3 [0, 3, 6, 9] >>> range(0, -10, -1) # 负数 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] >>> range(0) [] >>> range(1, 0) [] 

super(type[, object-or-type])

详细地看:http://www.runoob.com/python/python-func-super.html
简单地说就是为了安全地继承.记住怎么用的就行了.没必要深究.

#!/usr/bin/python # -*- coding: UTF-8 -*-   class A(object):   # Python2.x 记得继承 object     def add(self, x):          y = x+1          print(y) class B(A):     def add(self, x):         super(B, self).add(x) b = B() b.add(2)  # 3

print

print('name: "%s"' % props['name'],fp) //把字符串写入文件fp

random.choice(sequence)

https://pynative.com/python-random-choice/

  • random.choice 选中一个
  • random.sample(sequence,k=) 选中多个
import random path = "/home/train/disk/data/yulan_park_expand" random.choices([x for x in os.listdir(path)                if os.path.isfile(os.path.join(path, x))],k=2000)
from shutil import copyfile  copyfile(src, dst)
import argparse parser = argparse.ArgumentParser() parser.add_argument('num',type=int,help="img numbers to random") args = parser.parse_args() 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!