Python中列表元素与前一个元素比较及Paramiko多路径执行问题
Let's break down how to do this—there are a few simple, readable approaches depending on what you need to achieve with the comparison:
Basic For Loop (Great for Actionable Comparisons)
If you need to perform specific actions based on the comparison (like printing results or modifying elements), a straightforward loop is easy to follow:
my_list = [1, 3, 2, 5, 4] # Start from index 1 since the first element has no prior element for i in range(1, len(my_list)): current = my_list[i] previous = my_list[i-1] # Example: Check if current element is larger than the previous one if current > previous: print(f"Current value {current} is bigger than {previous}") else: print(f"Current value {current} is smaller or equal to {previous}")
List Comprehension (Concise for Boolean Results)
If you just want a list of boolean outcomes (e.g., whether each element is greater than the prior), list comprehension is perfect:
my_list = [1, 3, 2, 5, 4] # Pair each element with its predecessor using zip() comparison_results = [current > previous for current, previous in zip(my_list[1:], my_list)] print(comparison_results) # Output: [True, False, True, False]
Using Enumerate (For Index + Value Access)
If you need both the index and value of elements during comparison, enumerate is a handy tool:
my_list = [1, 3, 2, 5, 4] for idx, current in enumerate(my_list): if idx == 0: continue # Skip first element—it has no predecessor previous = my_list[idx-1] print(f"At index {idx}: {current} vs {previous}")
Looking at your code, I spot two key problems that are causing your parsing headaches. Let's fix them step by step:
Problem 1: Passing a list to sftp.listdir()
The sftp.listdir() method expects a single string path, not a list of paths. You need to loop through your path list one entry at a time.
Problem 2: Unnecessary use of exec_command for listing files
You don't need to run an SSH shell command to list files—SFTP has its own built-in methods to fetch directory contents, which are more reliable and avoid messy shell output parsing.
Corrected Code
Here's the fixed version that works as intended:
import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('hostname', username='test1234', password='test') paths = ['/home/test/', '/home/test1/','/home/test3/'] sftp = client.open_sftp() for path in paths: try: # Use SFTP's native listdir() to get files in the current path filenames = sftp.listdir(path) print(f"Files in {path}:") for filename in filenames: # Get full path if needed (avoids trailing slash issues) full_path = f"{path.rstrip('/')}/{filename}" print(full_path) except Exception as e: # Add error handling for missing paths or permission issues print(f"Failed to access {path}: {str(e)}") # Clean up connections to avoid resource leaks sftp.close() client.close()
Key Improvements:
- Loops through each path individually instead of passing the entire list to
listdir() - Uses SFTP's native file-listing method instead of shell commands (no more parsing stdout)
- Adds basic error handling for common issues like missing directories
- Properly closes SFTP and SSH connections when done
If you specifically need to run a shell command for each file (not just list them), you'd adjust the code to pass the full file path to exec_command—but for listing files, SFTP is the cleaner, more reliable choice.
内容的提问来源于stack exchange,提问作者Victory

