【问题标题】:I have a list of strings and I want to put every string through my code. How would I do that?我有一个字符串列表,我想将每个字符串都放在我的代码中。我该怎么做?
【发布时间】:2022-01-17 19:46:56
【问题描述】:

所以我有一个字符串列表,我想将每个字符串都放在我的代码中。我该怎么做?

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 部分

127.0.1.1
127.0.2.1
127.0.3.1
127.0.4.1

我希望它输出

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

【问题讨论】:

  • 我假设 List 是您问题中提到的 IP 地址的 Python 列表。但是你为什么要运行 44 个线程呢?此外, a = (Api + f) 不会帮助您。考虑一下并进行一些调试。你会发现它很有启发性

标签: python arrays string


【解决方案1】:

有很多方法可以实现这一点。这是其中之一:

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()

【讨论】:

    【解决方案2】:

    您可以在函数内循环并使用 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))
    

    【讨论】:

    • 如果我的列表不超过 1000 个不同的字符串,这将起作用
    • 抱歉没有澄清这一点
    • 假设列表是预定义的,将其作为参数传递给函数(检查编辑)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2022-07-20
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多