我的列表看起来像这样:
foo = ["neg * , This is a sentence","pos * , This is another sentence"]
我需要将句子拆分成一个值,即neg
或pos
,一个句子。
我试过了:
for text in foo:
text = text.split("*")
for a,b in text:
cat=a
text=b
然而,我得到了“太多的值来打开包装”,任何人都有想法?
答案 0 :(得分:6)
你的问题是你的循环构造得非常糟糕(这是可以原谅的,因为你显然是对整个事物的新手)
尝试这种更安全的方法(列表理解):
>>> foo = ["neg * , This is a sentence","pos * , This is another sentence"]
>>> [p.split('*', 1) for p in foo]
[['neg ', ' , This is a sentence'], ['pos ', ' , This is another sentence']]
现在您有一个[CAT, TEXT]
项目列表。
>>> l = [p.split('*', 1) for p in foo]
>>> for cat, text in l:
print 'cat: %s, text: %s' % (cat, text)
cat: neg , text: , This is a sentence
cat: pos , text: , This is another sentence
答案 1 :(得分:1)
第for a,b in text:
行不合适。更好的选择是a,b=text
。前面的代码在成对列表上运行,后者在一对上运行。
应用该建议并删除冗余:
foo = ["neg * , This is a sentence","pos * , This is another sentence"]
for text in foo:
a,b = text.split("*")
# Now do something with 'a' and 'b'
如果确实想要重新使用text
变量,则可行:
for text in foo:
a, text = text.split("*")
# Now do something with 'a' and 'text'
答案 2 :(得分:1)
你在内循环中做的赋值部分是错误的。在这里,试试这个
lines = ["neg * , This is a sentence","pos * , This is another sentence"]
for line in lines:
category, sentence = line.split("*", 1)
答案 3 :(得分:0)
你在第二个循环中迭代字符串
for text in foo:
text = text.split("*")
a,b = text:
在这种情况下,您将a分配给文本的第一个元素,b分配给第二个元素。 否则,您将字符串拆分为字符,并且您没有与字符数相同的变量数
答案 4 :(得分:0)
textList = []
catList = []
for str in foo:
(cat,text) = str.split('*')
textList.append(text)
catList.append(cat)
然后textList
是文本字符串列表,catList
是cat字符串列表。否则你将无法访问所有不同的猫和文本。