同时循环多个列表?

dan*_*rad -2 python loops

我正在寻找一些有关循环的帮助。我有一个名单,我希望使用随机用户输入的消息顺序向该列表中的每个个人资料发送消息。

理想情况下,这将涉及循环遍历 profileLink 项,同时循环遍历 nameList 项,以便我可以为每个配置文件构建一个新的 messageInput。

我的代码可以工作,但目前有很多重复,构建此代码以支持更大的列表将涉及大量复制和粘贴,如下所示 - 您会如何处理这个问题?

messageInput0="Hi " + f'{namelist[0]}' + ", " + f'{choice(messageOptions)}'
messageInput1="Hi " + f'{namelist[1]}' + ", " + f'{choice(messageOptions)}'
messageInput2="Hi " + f'{namelist[2]}' + ", " + f'{choice(messageOptions)}'
messageInput3="Hi " + f'{namelist[3]}' + ", " + f'{choice(messageOptions)}'
messageInput4="Hi " + f'{namelist[4]}' + ", " + f'{choice(messageOptions)}'

webbrowser.open(profileLink[0])
time.sleep(6)
pyautogui.press('tab')
pyautogui.write(messageInput0, interval=random.uniform(0.03, 0.15))

with pyautogui.hold('command'):
    pyautogui.press('w')

webbrowser.open(profileLink[1])
time.sleep(6)
pyautogui.press('tab')
pyautogui.write(messageInput1, interval=random.uniform(0.03, 0.15))

with pyautogui.hold('command'):
    pyautogui.press('w')

webbrowser.open(profileLink[2])
time.sleep(6)
pyautogui.press('tab')
pyautogui.write(messageInput2, interval=random.uniform(0.03, 0.15))

with pyautogui.hold('command'):
    pyautogui.press('w')

    webbrowser.open(profileLink[3])
time.sleep(6)
pyautogui.press('tab')
pyautogui.write(messageInput3, interval=random.uniform(0.03, 0.15))

with pyautogui.hold('command'):
    pyautogui.press('w')

    webbrowser.open(profileLink[4])
time.sleep(6)
pyautogui.press('tab')
pyautogui.write(messageInput4, interval=random.uniform(0.03, 0.15))

with pyautogui.hold('command'):
    pyautogui.press('w')
Run Code Online (Sandbox Code Playgroud)

编辑:尝试最佳答案后,我收到列表对象没有属性“替换”的错误

值得一提的是,我的列表是使用 str.replace/str.split 函数构建的,如下所示:

profileLink = open("profiles.txt").read().splitlines()

profileLink = [item.replace("+","name=") for item in profileLink]
newLinks = [item.replace("%","name=") for item in profileLink]
nameList = [i.split("name=")[1] for i in newLinks]
Run Code Online (Sandbox Code Playgroud)

编辑2:第一次编辑实际上是一个不相关的错误。现在修好了。

AKX*_*AKX 5

就像这样。

  • 用于zip“压缩”名称和个人资料链接,您不必跟踪循环索引。
import random
import time
import pyautogui
import webbrowser

namelist = ["a", "b", "c", "d"]
profilelink = ["q", "w", "e", "r"]
messageOptions = ["bye", "hello"]

for name, link in zip(namelist, profilelink):
    message = f"Hi {name}, {random.choice(messageOptions)}"

    webbrowser.open(link)
    time.sleep(6)
    pyautogui.press("tab")
    pyautogui.write(message, interval=random.uniform(0.03, 0.15))

    with pyautogui.hold("command"):
        pyautogui.press("w")
Run Code Online (Sandbox Code Playgroud)