如何在Python

时间:2018-03-12 04:56:23

标签: string list join split

尝试仅加入包含数字的大型列表的部分。例如:

h = ['9 This is the way this is the way 10 to program a string 11 to program a string']
##I've tried...
h[0].split()
z = []
h = ['9', 'This', 'is', 'the', 'way', 'this', 'is', 'the', 'way', '10', 'to', 'program', 'a', 'string', '11', 'to', 'program', 'a', 'string']
for i in h:
    while i != '10':
        z.append(i)

但该程序运行无限循环。我也试过if语句,如果我!='10'然后是z.append(i)。基本上,我有大部分的经文作为单个字符串在列表中,我想快速提取经文并将它们放在他们自己的单独列表中。谢谢

编辑:我试过......

h= ['9 nfnf dhhd snsn nana na 10 hfhf gkg utu 11 oeoe ldd sss', 'kgk hfh']
y = h[0].split()
print (y)
z = []
for i in y:
    if i != "10":
       z.append(i)
       break
print (z)

输出是拆分列表,'z'仅打印'9'。我还将中断更改为'for'循环的正确缩进

2 个答案:

答案 0 :(得分:0)

首先,使用从h[0].split()获得的结果。您可以使用h = h[0].split()

执行此操作

现在,让我们进入循环。它会进入一个无限循环,因为for循环正在选择第一个i "9"然后while i != "10",它会不断追加i到{{1} }}。 z永远不会等于i。因此,无限循环。我想你想要的是:

"10"

这会将h的每个值附加到z,直到i等于“10”。如果您需要更多帮助,请告诉我,我很乐意进行编辑!

答案 1 :(得分:0)

尝试使用它来提取z中的所有数字:

h = ['9 This is the way this is the way 10 to program a string 11 to program a string']
##I've tried...
h = h[0].split()
z = []
for i in h:
    try:
        z.append(eval(i))
    except:
        pass

print z

输出:

[9, 10, 11]
[Finished in 0.0s]