有没有办法将 for 语句的内容传递给函数?

Is there a way to transfer the contents of a for statement to a function?

def encrypt():
  while True:
    try:
        userinp = input("Please enter the name of a file: ")
        file = open(f"{userinp}.txt", "r")
        break  
    except:
      print("That File Does Not Exist!")
  second = open("encoded.txt", "w")
  for line in file:
    swapped(line)
    break
  #second.write()  
 
def swapped(line):
  newword = ""
  arranged = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
  random = ["q","w","e","r","t","y","u","i","o","p","a","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m"]
  print(line)

所以我目前正在尝试制作一个加密然后解密文件的程序。对于加密过程,我试图将给定文件的一行移动到另一个函数,这将替换与文件中的单词相对应的排列列表中一个索引处的字母,并替换为同一索引处的字母,但 isstead在随机列表中。

到目前为止,我已经尝试在我的 while 语句末尾创建的 for 循环下调用交换函数,并且尽管成功地传输了文件中的所有内容,但是当对任何在第二个函数中给定列表,整个列表打印 9 次,这是给定文件中的行数。在上面,我试图让它在 for 循环下调用交换函数,但随后中断,它只将文件的一行传输到第二个函数,但使列表正常打印出字母。

现在我只需要帮助以一种方式传输我的文件的内容,即每一行都单独传送到交换函数,而且还需要列表正常工作以允许我交换值的方式。

我对 python 还是很陌生,所以不胜感激。

照原样,您的交换函数只是打印输入,因为您实际上并没有使用排列列表和随机列表。我建议将列表更改为字典:

def encrypt():
  while True:
    try:
        userinp = input("Please enter the name of a file: ")
        file = open(f"{userinp}.txt", "r")
        break  
    except:
      print("That File Does Not Exist!")
  second = open("encoded.txt", "w")
  encrypted_lines = []
  #Creates a list of encrypted lines
  for line in file:
     encrypted_line = swapped(line)
     encrypted_lines.append(encrypted_line)
  return encrypted_lines
  #TODO save to encrypted file instead of returning
 
def swapped(line):
    new_line = ""
    encrypt_dict =  {'a': 'q', 'b': 'w', 'c': 'e', 'd': 'r', 'e': 't', 'f': 'y', 'g': 'u', 'h': 'i',
    'i': 'o', 'j': 'p', 'k': 'a', 'l': 's', 'm': 'd', 'n': 'f', 'o': 'g', 'p': 'h',
        'q': 'j', 'r': 'k', 's': 'l', 't': 'z', 'u': 'x', 'v': 'c', 'w': 'v', 'x': 'b',
    'y': 'n','z': 'm'}
    for i in line:
        if i in list(encrypt_dict.keys()):
            new_line = new_line + encrypt_dict[i]
    return new_line
print(encrypt())