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

Python将任意数量列表元素拼接为字符串列表的高效实现方案

More Efficient Way to Concatenate Corresponding Elements into String Lists

Great question! Your current approach gets the job done, but we can streamline this process to be more concise, memory-efficient, and easier to read. Let’s break down the better alternatives:

The Core Issue with Your Current Approach

Your method first transposes the list of tuples with zip(*list_A), converts each column to a string list, then concatenates—this adds unnecessary intermediate steps and creates extra temporary data structures. Instead, we can work directly with the tuples in your original list_A.

The Simplified, Efficient Solution

Since each tuple in list_A already contains the exact elements you want to concatenate (one from each original list), we can process each tuple directly in a single list comprehension:

# Example list_A with mixed string/int/float types
list_A = [('some1', 'thing1'), ('some2', 2), ('some3', 3.14)]

# Customize the separator (e.g., '_', '-', ' ') as needed
separator = '_'
result = [separator.join(map(str, item)) for item in list_A]

print(result)
# Output: ['some1_thing1', 'some2_2', 'some3_3.14']

Why This Is Better

  • Fewer intermediate variables: No need for list_B or intermediate string sublists—we generate the final result in one pass.
  • Lower memory usage: We avoid creating transposed lists and extra string collections, which makes a big difference for large datasets.
  • Clearer logic: The code directly expresses what we’re doing: take each group of elements, convert them all to strings, then join with your chosen separator.
  • Flexibility: Swap out separator for any character/string (like '-' or ' ') without changing the core logic.

Bonus: Skip Creating list_A Entirely

If you originally created list_A by zipping multiple input lists (e.g., list_1, list_2), you can skip that step entirely and process the zipped pairs directly:

list_1 = ['some1','some2','some3']
list_2 = ['thing1','thing2','thing3']
list_3 = [100, 200, 300]  # Add as many lists as you need

separator = '_'
result = [separator.join(map(str, pair)) for pair in zip(list_1, list_2, list_3)]

print(result)
# Output: ['some1_thing1_100', 'some2_thing2_200', 'some3_thing3_300']

This cuts out the middleman of list_A entirely, making the code even more efficient.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:56:06