Lesson_01(format(),strip(),startswith(),any(),isalpha(),字典 get(),enumerate(),isinstance())

能向后看得越远就可能向前看得越远.(The farther backward you can look,the farther forward you are likely to see.)邱吉尔

list添加元素的操作

python中向list中添加元素的操作有4种:

  1. append() 添加元素到list的尾部,接受一个任意类型的参数,添加后保持类型不变
 list_one = ['a', 'b']
 list_one.append('c')
 print(list_one)
>>>['a', 'b', 'c']
list_one.append(['d', 'e'])
print(list_one)
>>>['a', 'b', 'c', ['d', 'e']]
  1. extend() 将一个列表中每个元素分别添加到另一个列表中,只接受一个参数;extend()相当于是将list B 连接到list A上.
 list_one = ['a', 'b']
 list_one.extend(['d', 'e'])
 print(list_one)
 >>>['a', 'b', 'd', 'e']
  1. insert() 将一个元素插入到列表中,参数有两个,第一个参数是插入的位置,第二个参数是插入的元素。
 list_one = ['a', 'b', 'd', 'e']
 list_one.insert(2, 'f')
 print(list_one)
 >>> ['a', 'b', 'f', 'd', 'e']
  1. 加号+,将两个list相加,返回到一个新的list对象。前三种方法是改变原数组,无返回值,但是这一种创建一个新的list对象,不改变原数组。
list_one = ['a', 'b', 'd', 'e']
list_two = ['f', 'g']
list_three = list_one + list_two
print(list_one)
print(list_two)
print(list_three)
>>>['a', 'b', 'd', 'e']
>>>['f', 'g']
>>>['a', 'b', 'd', 'e', 'f', 'g']

networkx库

NetworkX是一个用Python语言开发的图论与复杂网络建模工具,内置了常用的图与复杂网络分析算法,可以方便的进行复杂网络数据分析、仿真建模等工作。

import networkx as nx                         
G = nx.Graph()       
    #建立一个空的无向图G;可以带参数,创建一个有结点和边的图,参数是一个dictionary
G.add_node(1)         #添加一个节点1
G.add_edge(2,3)       #添加一条边2-3(隐含着添加了两个节点2、3)
G.add_edge(3,2)      #对于无向图,边3-2与边2-3被认为是一条边
print(G.nodes())          #输出全部的节点: [1, 2, 3]
print(G.edges())          #输出全部的边:[(2, 3)]
print(G.number_of_edges())          #输出边的数量:1 

更多的请参考博客复杂网络分析库NetworkX学习笔记

%matplotlib inline

这句话只在jupyter中用到,可以在那里面生成图像。

sorted() or sort()

  1. sort()是list方法,为给定列表按ASCII排序,排序改变原列表;可有也可无参数key或reverse
  2. sorted()是python中的排序函数,可有两个参数sorted(),一个是列表,一个是相应的函数,排序后不改变原列表

更多的请参考python中sorted方法和列表的sort方法使用详解

format()

字符串类型格式化采用format()方法,基本使用格式是:
<模板字符串>.format(<逗号分隔的参数>)

print('standing on {} Looking forward {}'.format('froniter', 'successors'))
>>>standing on froniter Looking forward successors

另外该函数还有另外一个用法:格式控制信息。请参考Python字符串格式化–format()方法

strip()

  1. 移除字符串首尾指定的字符(默认为空格或换行符)或字符序列。
  2. lstrip() 用法如上,只是移除指定字符
  3. rstrip() 用法如上,只是移除指定字符

homework

startswith()

  1. 该方法用于判断字符串是否以指定前缀开头,如果是则返回 True,否则返回 False。
  2. 语法:str.startswith(str, beg=0,end=len(string));
  3. 上述语法的参数:str – 检测的字符串。
    beg – 可选参数用于设置字符串检测的起始位置。
    end – 可选参数用于设置字符串检测的结束位置
str = "this is string example....wow!!!";
print str.startswith( 'this' );
print str.startswith( 'is', 2, 4 );
print str.startswith( 'this', 2, 4 );
>>>True
>>>True
>>>False

any() or all()

  1. any() 首先意思是任意。
  2. any(iterable)说明:参数iterable:可迭代对象;如果当iterable所有的值都是0、’’、或False时,那么结果为False,如果所有元素中有一个值非0、’’、或False,那么结果就为True
any((0, '', False))
any([1, 2, 3, 0])
any(['a', 'b'])
>>>False
>>>True
>>>True
  1. all()首先意思是全部
  2. all(iterable) 如果iterable的所有元素不为0、’’、False或者iterable为空,all(iterable)返回True,否则返回False;
all([])
all(())
all([1, 2, 3, 0])
all(['a', 'b'])
>>>True
>>>True
>>>False
>>>True

isalpha()

  1. 该方法检测字符串是否只由字母组成。
  2. 语法:str.isalpha() 无参数
  3. 返回值:如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False
str = "this";  # No space & digit in this string
print str.isalpha();

str = "this is string example....wow!!!";
print str.isalpha();
>>>True
>>>False

字典 get() 方法和 setdefault() 方法

  1. 这两种方法类似,返回指定键的值,如果键不在字典中,返回一个指定值,默认为None。
  2. 区别: setdefault() 返回的键如果不在字典中,会添加键(更新字典),而 get() 不会添加键。
D = {'Name': 'Runoob', 'Age': 27}
 
print ("Age 值为 : %s" %  D.get('Age'))
print ("Sex 值为 : %s" %  D.get('Sex', "NA"))
print ("Sex 值为 : %s" %  D.get('Sex'))
>>>Age 值为 : 27
>>>Sex 值为 : NA
>>>Sex 值为 : None

replace()

  1. 将字符串中的第一个参数替换成第二个参数,最后一个可选参数是替换次数
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
>>>thwas was string example....wow!!! thwas was really string
>>>thwas was string example....wow!!! thwas is really string

enumerate()

  1. enumerate在字典上是枚举、列举的意思
  2. 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),该函数将其组成一个索引序列,利用它可以同时获得索引和值。多用于在for循环中得到计数
  3. 还可以接收第二个参数,用于指定索引起始值
list_one = ["这", "是", "一个", "测试"]
for index, item in enumerate(list_one):
    print (index, item)
>>>
0 这
1 是
2 一个
3 测试

list_one = ["这", "是", "一个", "测试"]
for index, item in enumerate(list_one, 1):
    print (index, item)
>>>
1 这
2 是
3 一个
4 测试

isinstance()

  1. isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
  2. isinstance() 与 type() 区别:
    type() 不会认为子类是一种父类类型,不考虑继承关系。
    isinstance() 会认为子类是一种父类类型,考虑继承关系。
    如果要判断两个类型是否相同推荐使用 isinstance()。
  3. 语法:isinstance(object, classinfo)
  4. 上述两个参数:
    object – 实例对象。
    classinfo – 可以是直接或间接类名、基本类型或者由它们组成的元组。
a = 2
b = [2]
isinstance (a,int)
>>>True
isinstance (a,str)
>>>False
isinstance (a,(str,int,list))    # 是元组中的一个返回 True
>>>True
isinstance (b, list)
>>>True
class A:
    pass
 
class B(A):
    pass
 
isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

random模块的choice()

  1. 随机返回一个元素
import random

print ("从 range(100) 返回一个随机数 : ",random.choice(range(100)))
print ("从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : ", random.choice([1, 2, 3, 5, 9]))
print ("从字符串中 'lesson' 返回一个随机字符 : ", random.choice('lesson'))

>>>从 range(100) 返回一个随机数 :  68
>>>从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 :  2
>>>从字符串中 'Runoob' 返回一个随机字符 :  s

结语

lesson_01结束,如有不好的地方,还请朋友们指正,感谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值