简体   繁体   中英

Python - using list() and manipulating lists

I seem to have a problem with my list generating script. I'm trying to convert a string into a list of string-lists, in order to use it in a specific fonction.

For exemple I want to convert the string 'abc' to a : [['a'],['b'],['c']] . so the script i wrote was:

s='some string'
t=[[0]]*len(s)
for i in range(len(s)):
    t[i][0] = list(s)[i]
return t

the problem is that this returns [['g'],['g'],..,['g']] instead of [['s'],['o'],..,['g']) .

I found another way to achieve that, but i can't seem to find the problem of this script. So,if anyone could help me, i would really appreciate it. Thanks in advance.

[[0]] * len(s) doesn't do what you think it does, consider this better approach:

s = 'abc'
li = [[ch] for ch in s]
print(li)
>> [['a'], ['b'], ['c']]

This is a classic mistake: [[0]]*n creates a list of n references to a unique object [0] . Use this instead to create a list of n different objects all equal to [0] : [[0] for i in range(n)] . This way, you can then change the value of each of them without affecting the others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM