如何基于现有列表的单列在Python 2.7中创建新列表?
Got it, let's break down how to solve this with Python 2.7. You've got a list xlist full of dictionaries with duplicate name values (like 'linux1v'), each with their own id and last_checkin timestamp. Since you mentioned creating a new list based on a single column, I'll cover two common use cases you might need:
If you just want a simple list of all unique hostnames (the name column) without any extra data, here's how to do it while preserving order (important since Python 2.7 doesn't have ordered dicts by default):
# First, pull all name values from the original list all_names = [entry['name'] for entry in xlist] # Filter out duplicates while keeping the first occurrence order unique_names = [] seen_hosts = set() for name in all_names: if name not in seen_hosts: seen_hosts.add(name) unique_names.append(name) # Example output: ['linux1v', 'otherhost', ...] print(unique_names)
If you want to keep the full record for each host but only keep the one with the most recent last_checkin timestamp (way more useful for tracking active hosts), this code will do the trick:
# Use a dictionary to track the latest entry per hostname latest_host_records = {} for entry in xlist: hostname = entry['name'] # Compare the current entry's timestamp with the stored one (if exists) if hostname not in latest_host_records or entry['last_checkin'] > latest_host_records[hostname]['last_checkin']: # Overwrite with the newer record latest_host_records[hostname] = entry # Convert the dictionary values back to a list (this is your new filtered list) unique_latest_list = latest_host_records.values() # Optional: Sort the list by most recent check-in first unique_latest_list = sorted(unique_latest_list, key=lambda x: x['last_checkin'], reverse=True) # Example output will have one entry per hostname with the latest timestamp for item in unique_latest_list: print(item)
Quick Note
Since you're using Python 2.7, we avoid relying on Python 3.7+ features like insertion-ordered dicts, but the code above still works perfectly because we only update the dictionary entry when we find a newer timestamp. The last_checkin DateTime objects support direct comparison with >, so that logic is straightforward.
内容的提问来源于stack exchange,提问作者nixgeek

