输出第10000个素数:

from math import sqrt

def is_prim(number):
    if number < 2:
        return False
    for i in range(2, int(sqrt(number)) + 1):
        if number % i == 0:
            return False
    return True

def get_prim(nth):
    if nth==1:return 2
    x = 1
    odd = 3
    while True:
        if is_prim(odd):x += 1
        if x==nth:return odd
        odd+=2   #只算奇数

nth = int(input("Input nth prime: "))
print(get_prim(nth))

****************************************分割线****************************************

边读边写:逗号语法用来嵌套


with open('read me',encoding='utf8') as r,open('write me.log','r+',encoding='utf8') as w:
    for line in r:
        if '的' in line:
            w.write(line)    # line [:-1],不读取末尾的\n

相较【 for line in open(filepath).readlines()】 ,【 with open(filepath)  as f】 的优点:

with负责处理open和close文件,包括抛出内部异常。而for line in f,将文件对象f当做迭代对象,将自动处理IO缓冲和内存管理,这样就无需担心几个G的 大文件的处理了。

****************************************分割线****************************************

以0~9这10个数字生产5位数,各5位数内无重复数字:


t=list(range(10))
data=[int('%s'*3 %(x,y,z)) for x in t for y in t for z in t if (x!=0 and x!=y and x!=z and y!=z)]   #3位数

t=[str(x) for x in t]
import itertools
data1=[int(''.join(x)) for x in itertools.permutations(t,5) if x[0]!='0']   #元素内无相同字符,5位数
data2=[''.join(x) for x in itertools.combinations_with_replacement(t,5) if x[0]!='0']
data3=[''.join(x) for x in itertools.combinations(t,5)   if x[0]!='0']
data4=[a+b+c+d+e for a,b,c,d,e in itertools.product(t,t,t,t,t) if a!='0']   #笛卡尔积
print(len(data1),data1)

*********** ****** *分割线 ************ ******

由[1,6,3],得到[[1, 6, 3], [1, 6, 3], [1, 6, 3], [1, 6, 3], [1, 6, 3]]:

import itertools
ns = itertools.repeat([1,6,3], 5)
print(list(ns))

*********** ****** *分割线 ************ ******

以元素的出现次数降序排序,取前4项:

words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes',
      'the', 'eyes', 'not', 'around', 'the', 'my', 'eyes', "you're", 'under',  'eyes', "don't",
    'look', 'around', 'the', 'eyes', 'look', 'into' ]

from collections import Counter
print(Counter(words).most_common(4))