提问人:Luchian Grigore 提问时间:12/11/2014 更新时间:12/13/2014 访问量:76
遍历 python 字符串数组会给出意外的输出
Iterating through python string array gives unexpected output
问:
我正在调试一些 python 代码,并且像任何乞丐一样,我正在使用 print 语句。我将问题范围缩小到:
paths = ("../somepath") #is this not how you declare an array/list?
for path in paths:
print path
我本来以为整个字符串都会打印出来,但只是这样。由于我计划无论如何扩展它以涵盖更多路径,因此似乎.
paths = ("../somepath", "../someotherpath")
修复了该问题并正确打印出两个字符串。
我假设初始版本将字符串视为字符数组(或者这可能只是我所说的 C++)并打印出字符。?...??
我仍然想知道为什么会这样。
答:
5赞
thefourtheye
12/11/2014
#1
("../somepath")
只不过是括号里覆盖的字符串。所以,它与 相同。由于 Python 的循环可以遍历任何可迭代对象,而字符串恰好是可迭代对象,因此它一次打印一个字符。"../somepath"
for
若要创建包含一个元素的元组,请在末尾使用逗号
("../somepath",)
如果要创建列表,则需要使用方括号,如下所示
["../somepath"]
评论
1赞
Padraic Cunningham
12/11/2014
OP 想要创建一个数组/列表
0赞
vks
12/11/2014
#2
paths = ["../somepath","abc"]
这样你就可以创建列表了。现在你的代码就可以工作了。
paths = ("../somepath", "../someotherpath")
这在形成元组时起作用了。这又是一种不可变列表。
0赞
Gabriel
12/11/2014
#3
经过测试,输出为每行一个字符
所以所有的东西都是每个字符打印一个字符
为了得到你想要的,你需要的
# your code goes here
paths = ['../somepath'] #is this not how you declare an array/list?
for path in paths:
print path
评论
()
用于元组,list 是[]
["../somepath"]
{}
a=3,4,5