Python列表和字符串的总结

1.Python列表list操作方法:

1.1 split()函数

语法:str.split(str=" ",num=string.count(str))[n]

参数说明:

  • str: 表示为分隔符,默认为空格,但是不能为空( ”)。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
  • num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量 [n]:
  • 表示选取第n个分片

注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略


str="hello boy<[www.doiido.com]>byebye"

print(str.split("[")[1].split("]")[0])
www.doiido.com

print(str.split("[")[1].split("]")[0].split("."))
['www', 'doiido', 'com']

一个简单的Example:

目的是在混杂有文本和数字的txt文件中读取数字,作图。(其实是在用sklearn做神经网络训练过程的一个输出)

import pandas as pd
import numpy as np
data=pd.read_table('learning.txt',header=None)
data = data.drop([i for i in range(1,254,2)])
data=np.array(data[0]).tolist()
x=[]
y=[]
x_=[]
y_=[]
for i in data:
    a=i.split(',',1)[0]
    b=i.split(',',1)[1]
    x_.append(a)
    y_.append(b)

for i in y_:
    a=i.split(' ',-1)[-1]
    y.append(a)
for i in x_:
    a=i.split(' ',-1)[-1]
    x.append(a)
x=[int(i) for i in x]
y=[float(i) for i in y]

import matplotlib.pyplot as plt
plt.figure(figsize=(16,9))
ax=plt.gca()
plt.plot(x, y)
ax.tick_params(labelcolor='k', labelsize='20', width=3)
plt.legend(labels=['learning curve'],loc=0,prop={'size': 20})
ax.set_xlabel('Iterations', size='20')
ax.set_ylabel('Loss', size='20')
plt.show()

fig

learning.txt 文件内容:

Iteration 1, loss = 1.07707919
Validation score: -0.759675
Iteration 2, loss = 0.86785333
Validation score: -0.382800
Iteration 3, loss = 0.65217935
Validation score: -0.036673
Iteration 4, loss = 0.47041240
Validation score: 0.245380
Iteration 5, loss = 0.33352409
Validation score: 0.448944
Iteration 6, loss = 0.24185446
Validation score: 0.586900
…….
Iteration 123, loss = 0.00163614
Validation score: 0.980205
Iteration 124, loss = 0.00163212
Validation score: 0.980224
Iteration 125, loss = 0.00162852
Validation score: 0.980240
Iteration 126, loss = 0.00162528
Validation score: 0.980255
Iteration 127, loss = 0.00162238
Validation score: 0.980269

2.Python的字符串操作方法:

2.1 strip() 方法

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。
语法:str.strip([chars])
移除字符串chars头尾指定的字符。

str = "0000000     Runoob  0000000"
print(str.strip( '0' ))  # 去除首尾字符 0


str2 = "   Runoob      "   # 去除首尾空格
print(str2.strip())

猜你喜欢

转载自blog.csdn.net/maverick_7/article/details/79111801