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

如何将列表索引转为列表?字符串转列表后嵌套子列表遇问题

Fixing Your String-to-Nested-List Conversion Issue

Hey there! I see the problem you're running into—your loop isn't updating the original string_list like you expect. Let's break this down and fix it.

What's Wrong With Your Current Code?

When you loop with for i in string_list:, the variable i is just a temporary copy of each element in the list. When you set i = list(i), you're only modifying this temporary variable, not the actual element stored in string_list. That's why your original list stays unchanged after the loop.

Solution 1: Modify the List Directly Using Indexes

Use enumerate() to get both the index and each character, then update the list at that index:

# Define the string
string = "Hello there!"
# Print string (Hello there!)
print(string)
# Define string_list and assign it to the list version of a string
string_list = list(string)
# Print original string_list
print("Original list:", string_list)

# Update each element to be a sublist
for idx, char in enumerate(string_list):
    string_list[idx] = list(char)

# Print the updated list
print("Updated list:", string_list)

Solution 2: Use a List Comprehension (Cleaner & More Pythonic)

For a more concise approach, skip the loop entirely and use a list comprehension to build your nested list in one line:

string = "Hello there!"
print(string)

# Directly create the nested list
string_list = [list(char) for char in string]

print(string_list)

What You'll Get

Both solutions will output this nested list:
[['H'], ['e'], ['l'], ['l'], ['o'], [' '], ['t'], ['h'], ['e'], ['r'], ['e'], ['!']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:34:08