python下标遍历字典_字典的遍历以及公共方法

目录

遍历

字符串的遍历

列表遍历

元组遍历

字典遍历

1> 遍历字典的key(键)

2> 遍历字典的value(值)

3> 遍历字典的项(元素)

补充

实现带下标索引的遍历,方法一

实现带下标索引的遍历,方法二(enumerate())

公共方法

运算符

+

*

in

Python内置函数

len

max

del

遍历

通过for……in……可以遍历字符串、元组、列表、字典等数据结构。

字符串的遍历

hya_str="welcome to china"

for char in hya_str:

print(char,end=' ')

##运行结果

w e l c o m e t o c h i n a

列表遍历

hya_list=[1,2,3,4,5]

for num in hya_list:

print(num,end=' ')

##运行结果

1 2 3 4 5

元组遍历

hya_turple=(1,2,3,4,5)

for num in hya_turple:

print(num,end=' ')

##运行结果

1 2 3 4 5

字典遍历

1> 遍历字典的key(键)

hya_dict={'name':'韩大本事','age':'25'}

for key in hya_dict.keys():

print(key,end=' ')

##运行结果

name age

2> 遍历字典的value(值)

hya_dict={'name':'韩大本事','age':'25'}

for value in hya_dict.values():

print(value,end=' ')

##运行结果

韩大本事 25

3> 遍历字典的项(元素)

hya_dict={'name':'韩大本事','age':'25'}

for item in hya_dict.items():

print(item,end=' ')

##运行结果

('name', '韩大本事') ('age', '25')

补充

实现带下标索引的遍历,方法一

hya_chars=['a','b','c','d']

i=0

for char in hya_chars:

print("%d %s"%(i,char))

i=i+1

##运行结果

0 a

1 b

2 c

3 d

实现带下标索引的遍历,方法二(enumerate())

hya_chars=['a','b','c','d']

for i, chr in enumerate(hya_chars):

print(i,chr)

##运行结果

0 a

1 b

2 c

3 d

公共方法

运算符

运算符

python表达式

结果

描述

支持的数据类型

+

[1, 2] + [3, 4]

[1, 2, 3, 4]

合并

字符串、列表、元组

*

'Hi!' * 4

['Hi!', 'Hi!', 'Hi!', 'Hi!']

字符串、列表、元组

in

3 in (1, 2, 3)

True

元素是否存在

字符串、列表、元组、字典

not in

4 not in (1, 2, 3)

True

元素是否不存在

字符串、列表、元组、字典

+

a=[1,2]

b=[3,4]

print(a+b)

##运行

[1, 2, 3, 4]

*

a=[1,2]

print(a*4)

#运行如下

[1, 2, 1, 2, 1, 2, 1, 2]

in

hya_str="hello"

if 'he' in hya_str:

print("true")

##运行

true

######注意:判断字典的时候判断的是键

Python内置函数

序号

方法

描述

1

cmp(item1, item2)

比较两个值

2

len(item)

计算容器中元素个数

3

max(item)

返回容器中元素最大值

4

min(item)

返回容器中元素最小值

5

del(item)

删除变量

len

hya_str="welcome to china"

print(len(hya_str))

##运行

16

max

hya_list=[1,23,4353,67]

print(max(hya_list))

##运行

4353

del

##del有两种用法,一种是del加空格,另一种是del()

a=25

del a

b=['a','b']

del b[0]

print(b)

print(a)

##运行

Traceback (most recent call last):

File "F:\python\pythongj\hya\温故而知新\练习ing.py", line 121, in print(a)

NameError: name 'a' is not defined

['b']

猜你喜欢

转载自blog.csdn.net/amberom/article/details/120041425
今日推荐