私信  •  关注

user2668284 user2668284

user2668284 user2668284 最近创建的主题
user2668284 user2668284 最近回复了
3 年前
回复了 user2668284 user2668284 创建的主题 » 如何使python程序运行得更快?我收到“9号死亡”信息,代码如下

这可以简化为:

N, M, O = [1766445895], [1], [1]
n, m, o = N[0], M[0], O[0]

while n > 0:
    n = (n-2)//2 if n % 2 == 0 else (n-1)//2
    N.append(n)
    if n % 2 == 0:
        o += m
    else:
        m += o
    O.append(o)
    M.append(m)

for i, (_n, _o, _m) in enumerate(zip(N, O, M)):
    print(f'{i}:  n = {_n:10d}, q = {_o:6d}/{_m:6d}')

你可以这样做:-

import json

def main(filename):
    payload = {}
    ch = None
    jt = []
    with open(filename) as txt:
        for line in txt.readlines():
            if line.startswith('['):
                if ch and jt:
                    payload[ch] = json.loads(''.join(jt))
                    jt = []
                ch = line[1:line.index(']')]
            else:
                jt.append(line.strip())
        if ch and jt:
            payload[ch]=json.loads(''.join(jt))
    print(json.dumps(payload, indent=4))


if __name__ == '__main__':
    main('test.txt')
3 年前
回复了 user2668284 user2668284 创建的主题 » for循环中的Python多处理

以下是你可以适应的模式:

from concurrent.futures import ProcessPoolExecutor

def func1(a, b):
    pass

def func2(a, b):
    pass

def func3(a, b):
    pass

def main():
    with ProcessPoolExecutor() as executor: # work manager
        for i in range(1_000):
            futures = []
            for func in [func1, func2, func3]:
                futures.append(executor.submit(func, i, i))
            for future in futures:
                future.result() # wait for process to terminate

if __name__ == '__main__':
    main()
4 年前
回复了 user2668284 user2668284 创建的主题 » 使用Python并发处理1000个链接。期货

下面是一个使用线程模块的示例:-

import requests
import threading

Product_Category = []
Date = []
Product_name = []
Reference = []
AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_5_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15'
BASEURL = 'https://webgate.ec.europa.eu/rasff-window/backend/public/notification/view/id/'
LOCK = threading.Lock()

headers = {'User-Agent': AGENT}
links = ['485387',
         '485256',
         '487113',
         '486733',
         '486937',
         '486946',
         '485444',
         '487258',
         '487011',
         '487254']


def scrape(session, link):
    response = session.get(f'{BASEURL}{link}/', headers=headers)
    response.raise_for_status()
    json = response.json()
    try:
        LOCK.acquire()
        Product_Category.append(
            json["product"]["productCategory"]["description"])
        Date.append(json["ecValidationDate"])
        Product_name.append(json["product"]["description"])
        Reference.append(json["reference"])
    finally:
        LOCK.release()


def main():
    with requests.Session() as session:
        ta = []
        for link in links:
            t = threading.Thread(target=scrape, args=(session, link))
            ta.append(t)
            t.start()
        for t in ta:
            t.join()
        print(Product_Category)
        print(Date)
        print(Product_name)
        print(Reference)


if __name__ == '__main__':
    main()
3 年前
回复了 user2668284 user2668284 创建的主题 » 在Python中,如何在打印时解压缩嵌套列表中的子列表

要获得所需的输出,可以执行以下操作:

sl=[[1,2,3],[4,5,6],[7,8,9]]
print('\n'.join([str(x) for y in sl for x in y]))