You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中列表元素与前一个元素比较及Paramiko多路径执行问题

1. Comparing Each List Element with Its Predecessor in Python

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}")

2. Fixing Your Paramiko/SFTP Code Issue

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:21:49