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

如何设计含唯一名称、Age与不定数量标签的可导出Data Structure?

Hey there! Let's break this down step by step since you're just starting out—this is a super common use case, so you're in the right place.

1. Pick a Structured Data Structure

For your needs, a custom class (or a dictionary if you want something simpler) is perfect. Classes let you bundle each entry's properties neatly, making it easy to add functionality later. Here's a Python example (since it's beginner-friendly):

class PersonEntry:
    def __init__(self, name, age, descriptors):
        # Enforce unique names (we'll add a check for this below)
        self.name = name
        self.age = age
        # Store tags as a set to avoid duplicates, or list if you care about order
        self.descriptors = set(descriptors) if isinstance(descriptors, list) else {descriptors}

# Initialize your sample data
entries = [
    PersonEntry("Jim", 47, ["Fat", "Tall", "Wrinkly"]),
    PersonEntry("Bob", 88, ["Sad"]),
    PersonEntry("Charlie", 12, ["Tall", "Ugly"])
]

To make sure names stay unique, add a quick check when creating new entries:

used_names = set()

class PersonEntry:
    def __init__(self, name, age, descriptors):
        if name in used_names:
            raise ValueError(f"Name '{name}' is already taken!")
        self.name = name
        used_names.add(name)
        self.age = age
        self.descriptors = set(descriptors) if isinstance(descriptors, list) else {descriptors}

2. Export to a Universal Format

You're right—CSV gets messy with variable-length tags. JSON is the way to go: it supports nested lists (perfect for tags) and works with every programming language. Here's how to export your data:

import json

def export_to_json(entries_list, filename):
    # Convert class instances to dictionaries for JSON serialization
    export_data = []
    for entry in entries_list:
        export_data.append({
            "name": entry.name,
            "age": entry.age,
            "descriptors": list(entry.descriptors)
        })
    
    with open(filename, 'w') as file:
        json.dump(export_data, file, indent=4)  # Indent makes it human-readable

# Use it like this
export_to_json(entries, "people_data.json")

The output JSON will look clean and easy to import later:

[
    {
        "name": "Jim",
        "age": 47,
        "descriptors": ["Fat", "Tall", "Wrinkly"]
    },
    {
        "name": "Bob",
        "age": 88,
        "descriptors": ["Sad"]
    }
]

3. Add Tag View & Search Functions

These are straightforward to implement with basic loops:

View All Unique Tags

def get_all_unique_tags(entries_list):
    all_tags = set()
    for entry in entries_list:
        all_tags.update(entry.descriptors)
    return sorted(all_tags)  # Sort for readability

# Example usage
print("All unique tags:", get_all_unique_tags(entries))
# Output: All unique tags: ['Fat', 'Sad', 'Tall', 'Ugly', 'Wrinkly']

Search Entries by Tag

def search_by_tag(entries_list, target_tag):
    matches = []
    # Make search case-insensitive (optional but user-friendly)
    target_tag_lower = target_tag.lower()
    for entry in entries_list:
        if target_tag_lower in [tag.lower() for tag in entry.descriptors]:
            matches.append(entry)
    return matches

# Example: Find everyone tagged "Tall"
tall_people = search_by_tag(entries, "Tall")
for person in tall_people:
    print(f"{person.name}, Age: {person.age}")
# Output:
# Jim, Age: 47
# Charlie, Age: 12

Quick Notes for Other Languages

If you're not using Python, this structure translates easily:

  • In Java/C#, use a Person class with similar properties.
  • In JavaScript, use objects stored in an array.
  • For databases, you'd split this into two tables (one for people, one for tags) linked by IDs, but that's overkill for small projects.

Hope this helps you get started! Tweak the code to fit your preferred language—this core logic works everywhere.

内容的提问来源于stack exchange,提问作者rfii

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:10:20