[英]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']]
. 例如,我想将字符串
'abc'
转换为: [['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'])
. 问题是这会返回
[['g'],['g'],..,['g']]
而不是[['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: [[0]] * len(s)
没有做你认为它做的事情,考虑这个更好的方法:
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]
. 这是一个经典错误:
[[0]]*n
创建一个对唯一对象[0]
的n
引用的列表。 Use this instead to create a list of n
different objects all equal to [0]
: [[0] for i in range(n)]
. 改为使用它来创建一个
n
不同对象的列表,所有对象都等于[0]
: [[0] for i in range(n)]
。 This way, you can then change the value of each of them without affecting the others. 这样,您就可以在不影响其他值的情况下更改每个值的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.