注:部分 print 未带括号为 python 2.x 版本。 一、中文编码问题 import json dict1 = { 'School' : 'zhoubei' , 'Name' : '张三' , 'Age' : 7 , 'Class' : '第一班' } print dict1 [ 'School' ] print json . dumps ( dict1 ). dec
注:部分 print 未带括号为 python 2.x 版本。
一、中文编码问题
import jsondict1 = {'School':'zhoubei','Name': '张三', 'Age': 7, 'Class': '第一班'}
print dict1['School']
print json.dumps(dict1).decode('unicode-escape')
===处理 u'\u5468\661f\u9a83====
python3:str.encode('utf-8').decode('unicode_escape')
python2:str.decode('unicode_escape')
===处理 \xe5\x8d\x9a\xe9\x9b===
python3 默认编码Unicode
示例1
str.encode().decode('unicode_escape')encode('raw_unicode_escape').decode()
示例2:
s = u'\xe6\x97\xa0\xe5\x90\x8d'
s2 = s.encode('raw_unicode_escape')
若遇到问题以上方法都可以试一下,祝你好运
二、if /while 循环
print('-------输入三个数字,是否能组成三角形,并判断是什么三角形--------')n1 = int(raw_input('请输入第一个整数数字:'))
n2 = int(raw_input('请输入第二个整数数字:'))
n3 = int(raw_input('请输入第三个整数数字:'))
if n1 + n2> n3 and n2 + n3> n1 and n1 + n3> n2: #两边之和大于第三边
if n1 == n2 and n2 == n3:
print ('这是个等边三角形')
elif n1 == n2 or n2 == n3 or n1 == n3:
print ('这是个等腰三角形')
elif n1**2+n2**2 == n3**2 or n2**2 + n3**2 == n1**2 or n1**2 + n3**2 == n2**2: #符合勾股定理为直角三角形
print ('这是个直角三角形')
else:
print ('这是个普通的三角形')
else:
print ('无法组成三角形:')print('-----------------与电脑猜拳-------------------')
import random
import json
dict_c = {1:'石头',2:'剪刀',3:'布'}
dict_u = {'石头':1,'剪刀':2,'布':3}
user = raw_input('请输入:(只能是石头/剪刀/布)')
user1 = dict_u[user]
computer = random.randint(1,3)
c = dict_c[computer]
if user != '石头' and user != '剪刀' and user != '布':
print('你又调皮了,只能输入石头/剪刀/布')
else:
print('电脑出:')
print json.dumps(c).decode('unicode-escape')
print("输赢结果:")
if user == c:
print('平手')
elif user1 == 1 and computer == 3:
print('SB,你输啦')
elif user1 == 2 and computer == 1:
print('SB,你输啦')
elif user1 == 3 and computer == 2:
print('SB,你输啦')
else:
print('你走狗屎运了')
三、for 循环
# 公鸡3元/只,母鸡5元/只,小鸡每元3只print('-----------------100元买100只鸡-------------------')
for x in range(33): # 100元内,公鸡数不能超过33只
for y in range(20): # 同理,母鸡不能超过20只
for z in range(100): # 同理,小鸡不会超过100只
if 3 * x + 5 * y + (1.0 / 3) * z == 100 and x + y + z == 100:
print(x, y, z)#一对兔子每月生一对兔子,刚出生的兔子两个月后才能生育
print('--------------21个月兔子数量-----------------')
num1 = 2
num2 = 2
sum = 0
for i in range(1,21):
print ("第",i,"个月")
num1 = num2
num2 = sum
sum = num1+num2
print ("有", sum, "个兔子") #后一个月兔子的数量为前两个月兔子数量之和
print ("一共有",sum,"个兔子")#小明有一美元要买(1-100美分)东西,求出找零最少的情况
print('--------------找零钱-----------------')
buy = input('请输入买糖的价格1-100:')
count = 0
for a in range(0,5): # 25美分面额的 不能超过4张 (25×5>100)
for b in range(0,3): # 10美分面额的 不能超过2张 (10×3>25)这时可以给一张25美分面额的替代了
for c in range(0,2): # 5美分面额的 不能超过1张 (5×2=10) 这时可以用一张10美分面额的替代了
for d in range(0,5): # 1美分的 不能超过4张 (1×5=5) 这时可以给一张5 美分面额的替代
if a*25+b*10+c*5+d*1+buy == 100 and 10*b+5*c!=25 and 5*d+c!=10:
count = a + b + c + d
print ('找零%d个25美分 %d个10美分 %d个5美分 %d个1美分'%(a, b, c, d))
print ('一共', count, '个硬币')print('---------乘法口诀表-------------')
for i in range(1,10):
for j in range(1,i+1):
if i*j<10:
print i, '×', j, '=', i * j, ' ',
else:
print i,'×',j ,'=', i*j,'',
print ''
四、函数
print('-------输出不定个数的数字的和--------')sum_b = 0
sum_c = 0
sum_d = 0
def functionC(x,y,*args,**kwargs):
global sum_d
sum_b = x+y
sum_c= sum(args) #求和函数sum()必须传入可迭代对象
sum_d = sum_c+sum_b
return sum_d
functionC(1,2,3,4,5,6,7,8,9,10)
print sum_dprint('-------模拟range()全功能--------')
list_input = [2,9] #手动调制输入的range()
def range_1(*args):
if len(list_input)==1: #输入一个数字时
x0 = list_input[0]
list_output = []
i = 0
while x0>1 and i<x0:
list_output.append(i)
i+=1
else:
print ('输入的数字必须大于1')
return list_output
elif len(list_input)==2: #输入二个数字时
x0 = list_input[0]
x1 = list_input[1]
list_output = []
i = x0
if x0<x1:
while x1>0 and i<x1:
list_output.append(i)
i+=1
return list_output
else:
print('输入错误')
elif len(list_input)==3: #输入三个数字时
x0 = list_input[0]
x1 = list_input[1]
x3 = list_input[2]
list_output = []
i = x0
if x0<x1 and x3<x1:
while x1>1 and i<x1:
list_output.append(i)
i+=x3
return list_output
else:
print('输入错误')
else:
print ('你又调皮了,最多只能输入三个')
print (range_1(list_input))print('-----------互不相同且无重复数字的三位数-------------')
count = 0
list_b = 0
def third_num(list_a):
list_len = []
global count
for i in list_a:
for j in list_a:
for k in list_a:
if i!=j and j!=k and i!=k:
list_b =str(i)+str(j)+str(k)
list_len.append(list_b)
count+=1
return list_len
list_a = [1,2,3,4]
print third_num(list_a)
print ('三位数个数:',count)
五、冒泡排序 与 快速排序
# 冒泡排序两种写法(推荐第一种)def __sort1__(RowValue):
for i in range(len(RowValue)-1):
for j in range(len(RowValue)-1-i):
if RowValue[j]>RowValue[j+1]:
RowValue[j],RowValue[j+1]=RowValue[j+1],RowValue[j]
return RowValue
def __sort2__(list1):
for i in range(len(list1)):
for j in range(len(list1)-1):
if list1[i]<list1[j]:
list1[i],list1[j]=list1[j],list1[i]
return list1
list1 = [4,1,3,17,5,9,6,2]
RowValue = [4,1,3,17,5,9,6,2]
print('__sort1__(RowValue):',__sort1__(RowValue))
print('__sort2__(list1):',__sort2__(list1))print('=====================对三维数组排序(不改变元素列的位置)=========================')
aaa = np.array([[[929,533]],
[[ 67,534]],
[[ 67,136]],
[[906,136]],
[[123,156]]])
aaa2 = aaa.reshape(-1,2).tolist()
print('aaa2:\n',aaa2)
def __sort__(aaa2):
for i in range(len(aaa2)):
for j in range(len(aaa2)-1-i):
if aaa2[j][0]>aaa2[j+1][0]:
aaa2[j],aaa2[j+1]= aaa2[j+1],aaa2[j]
elif aaa2[j][0]==aaa2[j+1][0] and aaa2[j][1]>aaa2[j+1][1]:
aaa2[j], aaa2[j+1] = aaa2[j+1], aaa2[j]
return aaa2
aaa2 = __sort__(aaa2)
print('=======aaa2=============:\n',aaa2)
'''
=====================对三维数组排序(不改变元素列的位置)=========================
aaa2:
[[929, 533], [67, 534], [67, 136], [906, 136], [123, 156]]
=======aaa2=============:
[[67, 136], [67, 534], [123, 156], [906, 136], [929, 533]]
'''# -*- coding: utf-8 -*-
# =================================快速排序(方法1)=======================
def sub_sort(array,low,high):
key = array[low]
while low < high:
while low < high and array[high] >= key:
high -= 1
while low < high and array[high] < key:
array[low],array[high] = array[high],array[low]
low += 1
array[low] = key
return low
def quick_sort(array,low,high):
if low < high:
key_index = sub_sort(array,low,high)
quick_sort(array,low,key_index)
quick_sort(array,key_index+1,high)
if __name__ == '__main__':
array = [24, 26, 14, 2, 73,21]
print ('原:',array)
quick_sort(array,0,len(array)-1)
print ('现:',array)
# ===============================快速排序(方法2)========================
def QuickSort(myList,start,end):
if start < end: #判断low是否小于high,如果为false,直接返回
i,j = start,end
base = myList[i] #设置基准数
while i < j:
while (i < j) and (myList[j] >= base): #如果列表后边的数,比基准数大或相等,则前移一位直到有比基准数小的数出现
j = j - 1
myList[i] = myList[j] #如找到,则把第j个元素赋值给第个元素i,此时表中i,j个元素相等
while (i < j) and (myList[i] <= base): #同样的方式比较前半区
i = i + 1
myList[j] = myList[i]
myList[i] = base #做完第一轮比较之后,列表被分成了两个半区,并且i=j,需要将这个数设置回base
#递归前后半区
QuickSort(myList, start, i - 1)
QuickSort(myList, j + 1, end)
return myList
myList = [49,38,65,97,76,13,27,49]
print("Quick Sort: ")
QuickSort(myList,0,len(myList)-1)
print(myList)print('---------对元组内数字型元素求和-------------')
def fun(num1,num2,*agrs,**kwargs):
sum1 = 0
sum2 = 0
sum0 = int(num1.strip())+int(num2)
for i in agrs:
if str(i).strip().isdigit():
sum1 += int(i)
for j in kwargs.values():
if str(j).strip().isdigit():
sum2 += int(j)
num3 = sum0+sum1+sum2
return num3
a = fun(' 1', 2, 3, ' 4', 5, 'hello', a1=2, b1=3)
print (a)
六、字典--value2key
已知值values查找键keys:
student = {'小黑': '1001', 'Obama': '1002', '小强': '1003', '小明': '1004'}方法一:
a = list (student.keys()) [list (student.values()).index ('1004')]
print(a)
方法二:
new_dict = {v : k for k, v in student.items()}
print(new_dict['1001'])
方法三:
def get_key (dict, value):
return [k for k, v in dict.items() if v == value]
if __name__ == '__main__':
get_key (student, '1002')print('---------字典合并-------------')
def merge_two_dicts(x, y):
dict3 = {}
dict3 = dict1.copy()
dict3.update(dict2)
return dict3
dict1 = {'a':1,'b':2,'c':3,'d':'hello'}
dict2 = {'a':2,'b':'2','c':'she','e':'10','f':4}
print(merge_two_dicts(dict1,dict2))