python入门基础

2020-03-25  本文已影响0人  九月_1012

1、查看模块查找路径

>>> import sys
>>> sys.path
#增加查找路径
sys.path.append('/home/wang/workspace')

2、关于路径

import os
#获取当前目录
os.getcwd()

3、关于下载模块

export PYTHONPATH=$PYTHONPATH:/path/XXX/
#python 安装模块到指定的目录的几种表述
pip install numpy --target=/usr/local/lib/python2.7/site-packages
pip install --install-option="--prefix=$PREFIX_PATH" package_name
python  setup.py install  --prefix=~/local

4、读文件

file=argv[1]
with open file as f:
       for line in f:
          print(line)
      #close(f)  

5、两个列表组成一个字典

keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print dictionary
#把字典的键、值拆分成两个数组
# 初始化字典
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
# 将字典拆分为键和值的列表
keys = ini_dict.keys()
values = ini_dict.values()

6、遍历数组和字典

for i in range(len(lst)):   
   print lst[i]
for key in d:
    print key,
for key in d.iterkeys():
    # d.iterkeys(): an iterator over the keys of d
    print key,
for key in d.keys():
    # d.keys() -> ['y', 'x', 'z']
    print key,
for key, value in d.iteritems():
    # d.iteritems: an iterator over the (key, value) items
    print key,'corresponds to',d[key]
for key, value in d.items():
    # d.items(): list of d's (key, value) pairs, as 2-tuples
    # [('y', 2), ('x', 1), ('z', 3)]
    print key,'corresponds to',value

7、数组删除某个元素

1
li = [1, 2, 3, 4]
del li[3]
print(li)
# Output [1, 2, 3]
2
li = [1, 2, 3, 4]
li.pop(2)
print(li)
# Output [1, 2, 4]
3 按照具体的元素删除
li = [1, 2, 3, 4]
li.remove(3)
print(li)
# Output [1, 2, 4]
4 切片
li = [1, 2, 3, 4]
li = li[:2] + li[3:]
print(li)
# Output [1, 2, 4]

8、按照key sort字典

In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

9、多个空格分隔字符串

id=line.split()[1]

10 python 自己写模块

# 假设模块叫nester.py
def print_lol(the_list):
    for each_item in the_list:
        if isinstance(each_item, list):
          print_lol(each_item)
        else:
          print(each_item)
--------------------------------
1、mkdir nester
2、cd nester && vi setup.py
#Import the “setup” function from Python’s distribution utilities

from distutils.core import setup
setup(
    name='nester',
    version='1.0.0'
    py_modules = ['nester']
    author='XXX'
    author_email = 'XXX@foxmail.com'
    url='http://www.XXX.com'
    sescription='A simple printer of nested lists'
    )
3、python3 setup.py sdist
4、python3 setup.py insall
--------------------------------
模块可以用了
import nester
nester.print_lol("XXX")

11 替换、format

key = fields[1].strip(":").replace(" ","_")
value = "{0:.2f}%".format(10*float(value[0:6]))
value = "{:,}".format(int(value))

12 文件操作 os模块

stat_path = os.path.join(self._proj_path,"stat")
file_list = [i for i in os.listdir(stat_path) if i.endswith(end_with)]
        num_of_matchs = len(file_list)
        if num_of_matchs > 1:
            raise RuntimeError("Only one {} file is supported now".format(end_with))
        else:
            first = os.path.join(stat_path, file_list[0])
        return first

13 时间

from datetime import datetime
datetime.now().strftime("%Y-%m-%d")

14 报错,字符和数字之间使用“+”,需要转数字为str

wrong:
  f.write(key + "\t" + value + "\n" + key2 + "\t" + value2 + "\n")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
right:
    f.write(str(key) + "\t"  + str(key2) + "\t" + str(value2) + "\n")

15 创建二维字典

for i in {1..100}:
  dict.setdefault(i,{})      ##这里默认n不在字典里,则创建进去
dict[n]['num']=XXX

16 比如输出文件是给定的名字,需要用%s %,表明变量

open("%s/out.xls" % (opt.od))

17

infiles = os.listdir(inpath)
for fi in infiles:#fi并不是文件,必须加上路径名字,和perl不一样
if not os.path.isdir(inpath+"/"+fi):

18 读取文件存入二位字典,遍历字典,打印

filename = 'test.res'
out="out.list"
def make_dict(filename
    d={}
  #  with open(filename, 'r') as f:
  #    line = f.readlines()
for line in open(filename, 'r'):
        while line:
            eachline = line.split()
            sample = eachline[3]
            gene = eachline[0]
            ress = eachline[1:2]
            res = ("\t").join(ress)
            if sample not in d:
                d[sample]={}    #先定义第一层,这个和perl不一样
                if gene not in d[sample]:
                    d[sample][gene]=[res]
                else:
                    d[sample][gene].append(res)
            else:
                if gene not in d[sample]:
                   d[sample][gene]=[res]
                else:
                    d[sample][gene].append(res)
            line = f.readline()
    return d

def print_dict(_dict,filepath):

    with open(filepath, 'w') as f:

        for (key,values) in _dict.items():

            f.write("%s\t" %(key))

            for (gene,value2) in values.items():

                f.write("%s\t%si\t" % (gene,value2))

            f.write("\n")

if __name__ == '__main__':

    d=make_dict(filename)

    print_dict(d,out)

0 基础写法

#!/usr/bin/python

# -*- coding:utf-8 -*-

import os

print(os.path.abspath('.'))

print(__file__)

import sys

print(sys.argv)#打印参数

print(sys.executable) #python path

20、数组字符串互转

str = ','.join(arr)
arr = str.split(',')
上一篇 下一篇

猜你喜欢

热点阅读