如何将列表索引转为列表?字符串转列表后嵌套子列表遇问题
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

