当前位置 : 主页 > 编程语言 > python >

Python小知识点(5)

来源:互联网 收集:自由互联 发布时间:2022-06-24
全排列的实现 import itertools List = [1, 2, 3] permutation = list(itertools.permutations(List, len(List))) for i in permutation: ... print(i) ... (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) N进制转换为M进制 def

全排列的实现

>>> import itertools
>>> List = [1, 2, 3]
>>> permutation = list(itertools.permutations(List, len(List)))
>>> for i in permutation:
... print(i)
...
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

N进制转换为M进制

def transform():
str = input("please enter N, M\n")
N, M = str.split(",")
N = int(N); M = int(M)
x = input("enter number\n")
"""
将N进制数转化为10进制
保存于inter
"""
inter = 0
for i in range(len(x)):
inter += int(x[-1 -i]) * pow(N, i)

stack = []
while inter:
temp = inter % M
if temp >= 10:
stack.append(chr(65 + temp - 10))
else:
stack.append(temp)
inter //= M

for i in range(len(stack)):
print(stack[-1 - i], end="")

小数变分数

import fractions
def exec_24():
value_list1 = [1, 2]
for i in range(2, 30, 1):
value_list1.append(value_list1[i - 1] + value_list1[i - 2])

value_list2 = value_list1[1:]
s = 0
for i in range(20):
s += value_list2[i] / value_list1[i]
print(fractions.Fraction(s))

remove()与pop()

l = [1, 2, 3]

l
Out[16]: [1, 2, 3]

l.pop(2)
Out[17]: 3

l
Out[18]: [1, 2]

l.remove(1)

l
Out[20]: [2]

Python字符串格式化-format()

"{0:.2f}".format(12345.67890)
Out[29]: '12345.68'

"{0:H^20.3f}".format(12345.67890)
Out[30]: 'HHHHH12345.679HHHHHH'

"{0:.4}".format("PYTHON")
Out[31]: 'PYTH'

s = "PYTHON"

"{0:30}".format(s)
Out[17]: 'PYTHON '

"{0:>30}".format(s)
Out[18]: ' PYTHON'

"{0:*^30}".format(s)
Out[19]: '************PYTHON************'

"{0:-^30}".format(s)
Out[20]: '------------PYTHON------------'

"{0:3}".format(s)
Out[21]: 'PYTHON'


"{0:-^20,}".format(1234567890)
Out[24]: '---1,234,567,890----'

"{0:-^20}".format(1234567890) #对比输出
Out[25]: '-----1234567890-----'

"{0:-^20,}".format(12345.67890)
Out[26]: '----12,345.6789-----'


"{}{}{}".format("圆周率是",3.1415926,"...")
Out[11]: '圆周率是3.1415926...'

"圆周率{{{1}{2}}}是{0}".format("无理数",3.1415926,"...")
Out[12]: '圆周率{3.1415926...}是无理数'

s="圆周率{{{1}{2}}}是{0}" #大括号本身是字符串的一部分

s
Out[14]: '圆周率{{{1}{2}}}是{0}'

s.format("无理数",3.1415926,"...") #当调用format()时解析大括号
Out[15]: '圆周率{3.1415926...}是无理数'


网友评论