字典遍历操作
info = {'name': 'eric', 'age': 19, 'scores': [66, 77, 88]}
print(list(info.keys()))
print(list(info.values()))
print(list(info.items()))
for k, v in info.items():
print(f"k = {k} , v = {v}")
ls = [('name', 'eric'), ('age', 19), ('scores', [66, 77, 88])]
print(ls)
print(dict(ls))
import string
from random import randint
print(string.ascii_letters)
print([f'Student{i}' for i in string.ascii_letters[26:34]])
scores = {f'Student{i}': randint(10, 100) for i in string.ascii_letters[26:34]}
print(scores)
jige_d = {}
for k, v in scores.items():
if v >= 60:
jige_d[k] = v
print(jige_d)
print({k: v for k, v in scores.items() if v >= 60})
d = {}
print(d)
d['ha'] = 100
d['haa'] = 100
d['haaa'] = 100
print(d)
字符串常用操作方法
name = "C++ Java Python"
print(name.find("+"))
print(name.find("J"))
print(name.find("L"))
name2 = " C++ Java Python "
print(len(name))
print(len(name2))
name2 = name2.strip()
print(len(name2))
word_ls = name.split(" ")
print(word_ls)
s = '/usr/local/bin/python3.7 /Users/ericli/CLionProjects/jinlou/day11-python/Demo6.py'
print(s.split('/'))
print(s.replace('/', '\\'))
ws = ['C++', 'Java', 'Python']
print(" ".join(ws))
print("".join(ws))
print("\\".join(ws))
print("/".join(ws))
print("_".join(ws))
print(" ".join([str(i) for i in range(10)]))
词频统计案例
word_d = {}
with open('geci.txt') as f:
data = f.read()
print(data)
print(type(data))
ws = data.split()
print(ws)
for word in ws:
word_d[word] = 0
print(word_d)
for word in ws:
word_d[word] +=1
print(word_d)
print(word_d)
集合
s1 = {11, 222, 222, 666, 666, 666, '哈哈'}
print(s1)
print(type(s1))
from random import randint
data = [randint(0, 3) for i in range(1000)]
print(data)
print(set(data))
s1.add('哈哈')
s1.add('xixi')
s1.add('xixi')
print(s1)
print(s1.pop())
print(s1.pop())
print(s1)
for x in s1:
print(x)
函数
def hello():
print("Hello !")
print(hello())
from random import random
def twoFloat():
return random(), random()
print(twoFloat())
def twoSum(x, y):
print("x + y = ", x+y)
twoSum(10, 20)
def cal(n):
sums = 0
for i in range(1, n+1):
sums+=i
return sums
print(cal(100))
print(cal(10))
print(cal(1))
print(cal(1000))
|