Python 碎片

Python tutorial

 

1.枚举enumerate

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print '#%d: %s' % (idx + 1, animal)
# Prints "#1: fish", "#2: dog", "#3: cat"

 

2.tuple数组

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print type(t)    # Prints "<type 'tuple'>"
print d[t]       # Prints "5"
print d[(1, 2)]  # Prints "1"

 

3.class类

class Greeter:


    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable


    # Instance method
    def greet(self, loud=False):
        if loud:
            print 'HELLO, %s!' % self.name.upper()
        else:
            print 'Hello, %s' % self.name


g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

4.array矩阵

import numpy as np


a = np.array([1, 2, 3])  # Create a rank 1 array
print type(a)            # Prints "<type 'numpy.ndarray'>"
print a.shape            # Prints "(3,)"
print a[0], a[1], a[2]   # Prints "1 2 3"
a[0] = 5                 # Change an element of the array
print a                  # Prints "[5, 2, 3]"


b = np.array([[1,2,3],[4,5,6]])   # Create a rank 2 array
print b.shape                     # Prints "(2, 3)"
print b[0, 0], b[0, 1], b[1, 0]   # Prints "1 2 4"

 

5.plot

import numpy as np
import matplotlib.pyplot as plt


# Compute the x and y coordinates for points on sine and cosine curves
x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)


# Plot the points using matplotlib
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.xlabel('x axis label')
plt.ylabel('y axis label')
plt.title('Sine and Cosine')
plt.legend(['Sine', 'Cosine'])
plt.show()

sine_cosine.png (396×281)

 

6.read 中文

import codecs

f=codecs.open(filename,encoding='utf-8')

line=f.readlines()

7.remove '\n'

str.replace('\n','')

8.

 

  1. import pandas as pd  
  2. a = ['one','two','three']  
  3. b = [1,2,3]  
  4. english_column = pd.Series(a, name='english')  
  5. number_column = pd.Series(b, name='number')  
  6. predictions = pd.concat([english_column, number_column], axis=1)  
  7. #another way to handle  
  8. save = pd.DataFrame({'english':a,'number':b})  
  9. save.to_csv('b.txt',index=False,sep=''

 

9

 

 

#!/usr/bin/python

import pandasas pd

data = pd.read_csv('data.csv',nrows =5)

print(data)

10

1 #!/usr/bin/python
2 #coding:utf-8
3 print "你好吗"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值