Python常见数据结构:字符串,列表,字典

常见数据结构:字符串

1. print(len(string)) 打印字符串长度

abc = 'qwer123'
print(len(abc))

Output:
7

2. string.title():string 中每个单词首字母大写

#!/usr/local/bin/env python

abc = 'hello world'
print(abc.title())


Output:
Hello World

3. string.lower() :小写 

    string.upper() :大写

#!/usr/local/bin/env python

abc = 'HELLO WORLD'
print(abc.lower())

Output:
hello world

4. #r 表示原始字符串

#!/usr/local/bin/env python

s1 = 'HELLO WORLD'
s2 = (r'\n123')

print(s1+s2)

Output:
HELLO WORLD\n123

常见数据结构:列表 List

1.切片标记法

#!/usr/local/bin/env python

L1 = [1,10,30,'HELLO','python']

#切片标记法
print(L1[0])
print(L1[1:3])
print(L1[2:])

Output:
1
[10, 30]
[30, 'HELLO', 'python']

2. string.append("new string")

#!/usr/local/bin/env python

l1 = [1,10,30,'HELLO','python']

l1.append("new word")
print(l1)

Output:
[1, 10, 30, 'HELLO', 'python', 'new word']

3.append 与 for 循环结合创建列表

#!/usr/local/bin/env python

#append 与 for 循环结合创建列表

abc = []

for i in range(1,50,3):
    abc.append(i)

print(abc)

Output:
    [1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49]

4. del删除

#!/usr/local/bin/env python

#del 删除

abc = [1,3,4,57]

del abc[3]

print(abc)

#Output:
    [1, 3, 4]

4. pop() 指定弹出某个元素

#!/usr/local/bin/env python

#pop 指定弹出某个元素

abc = [1,3,4,57]

abc.pop(1)

print(abc)

#Output:
    [1, 4, 57]

4.list.sort(): 排序

   print(sorted(list)): 临时排序

   list.sort(reverse= True): 降序排序

5.count() : 记录出现次数

#!/usr/local/bin/env python

#count 计数

abc = [1,7,3,5,7,6,3,4,57]

print(abc.count(7))

Output:
    2

常见数据结构:字典

Dictiontary: key-value 极快的查找速度,空间换取时间

  #!/usr/local/bin/env python

#字典: 创建一个字典,储存个人信息
dict1={'name':'张三','age':'30','city':'Beijing'}
print(dict1)

'''
Output:
    {'name': '张三', 'age': '30', 'city': 'Beijing'}
'''

#通过key获取某个元素的Value
print(dict1.get('age'))

'''
Output:
    30
'''
 
#给字典增加一个元素
dict1['gender']='male'
print(dict1)


#修改某个元素value
dict1['age']=35
print(dict1)

'''
Output:
    {'name': '张三', 'age': 35, 'city': 'Beijing', 'gender': 'male'}
'''

#删除字典的某个元素
del dict1['gender']
print(dict1)

'''
Output:
    {'name': '张三', 'age': 35, 'city': 'Beijing'}
'''

#items()
print(dict1.items())


'''
Output:
    dict_items([('name', '张三'), ('age', 35), ('city', 'Beijing')])
'''

#遍历字典

for key,value in dict1.items():
    print(key+':',value)

print('==========================')

print(dict1.keys())

print('==========================')

for value in dict1.values():
    print(value)

'''
Output:
    name: 张三
    age: 35
    city: Beijing
    ==========================
    dict_keys(['name', 'age', 'city'])
    ==========================
    张三
    35
    Beijing
    
'''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值