簡體   English   中英

我有一個字符串列表,我想將每個字符串都放在我的代碼中。 我該怎么做?

[英]I have a list of strings and I want to put every string through my code. How would I do that?

所以我有一個字符串列表,我想把每個字符串都放在我的代碼中。 我該怎么做?

import requests
import json
import threading
import random
import socket
import struct

i = 0

def fg():
  Api = "https://api.mcsrvstat.us/2/"
  f = (List)
  a = (Api + f)
  r = requests.get(a)
  h = r.json()
  print (json.dumps(h, indent = 2))
          
while i <= 10:
    t1 = threading.Thread(target=fg)
    t1.start()
    t2 = threading.Thread(target=fg)
    t2.start()
    t3 = threading.Thread(target=fg)
    t3.start()
    t4 = threading.Thread(target=fg)
    t4.start()

這將是字符串列表,我希望它們中的每一個都通過 fg 部分到 go

127.0.1.1
127.0.2.1
127.0.3.1
127.0.4.1

我想要它 output

https://api.mcsrvstat.us/2/127.0.1.1
https://api.mcsrvstat.us/2/127.0.2.1
https://api.mcsrvstat.us/2/127.0.3.1
https://api.mcsrvstat.us/2/127.0.4.1

您可以在 function 中循環並使用 f 字符串格式化正確的:

strings = ["127.0.1.1", "127.0.2.1", "127.0.3.1", "127.0.4.1", ......]
def fg(strings):

  for string in strings:
      Api = f"https://api.mcsrvstat.us/2/{string}"
      r = requests.get(Api)
      h = r.json()
      print (json.dumps(h, indent = 2))

有很多方法可以實現這一目標。 這是其中之一:

from concurrent.futures import ThreadPoolExecutor
import requests
import json

IP_ADDRESSES = ['127.0.1.1', '127.0.2.1', '127.0.3.1', '127.0.4.1']

def fg(ip_address):
    url = f'https://api.mcsrvstat.us/2/{ip_address}'
    with requests.Session() as session:
        try:
            (r := session.get(url)).raise_for_status()
            return json.dumps(r.json(), indent=2)
        except Exception as e:
            return e

def main():
    with ThreadPoolExecutor() as executor:
        for future in [executor.submit(fg, ip_address) for ip_address in IP_ADDRESSES]:
            print(future.result())

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM