所以我自学了如何编程。到目前为止,我无处可去。
我有一个代码,从文本文件中的一行,我把该行的每个单词放在一个列表中。我们说列表是info =[john,guard,single]
。我已成功将单词加载到列表中,但在下一个任务中遇到了一些问题。
我想得到每个单词并在句子中使用它
我到目前为止所做的就是
for word in info:
print "My name is ",word[1]
print "My job is " ,word[2]
print "I am ",word[3]
但我得到的只是 我叫o 我的工作是h 我是 有人可以帮帮我吗?
好的,所以这是代码:
def loginfo(self):
infolist = []
with open('user.txt') as f:
f = f.readlines()
for line in f:
if str(self.neim.get()) in line:
if str(self.posse.get()) in line:
for word in line.split():
infolist.append(word)
for word in infolist:
print word[]
答案 0 :(得分:5)
你可以沿着这些方向做点什么:
li=['My name is {}', "My job is {}", "I am {}"]
info=['john','guard','single']
for x, y in zip(li, info):
print x.format(y)
打印:
My name is john
My job is guard
I am single
或者,只使用一个模板:
print 'My name is {}\nMy job is {}\nI am {}'.format(*info)
答案 1 :(得分:1)
您不需要for
循环。你可以简单地说:
print "My name is ",info[0]
print "My job is " ,info[1]
print "I am ",info[2]
在循环中,您遍历列表并将其中的每个字符串分配给变量word
。然后,您使用索引方法[]
访问该单词。这就是为什么你得到的是单个字母而不是单词。此外,计算机从0开始计数而不是1,因此索引为:
[0,1,2,3]
所以当你使用这样的for循环时:
for word in info:
print(word[0])
会发生什么:
John
word[0]
答案 2 :(得分:0)
for word in info:
是循环。它的主体(缩进部分)将为info
的每个元素执行一次。
您可以按索引访问info
个元素,正如其他答案所示。您还可以将列表解压缩到合理命名的变量中:
name, job, marital_status = info # the unpacking: 3 variables for 3 list items
print "My name is", name, "my job is", job, "I am", marital_status
当您有要处理的人员列表时,循环会派上用场:
people = [ # a list of lists
["Joe", "painter", "single"],
["Jane", "writer", "divorced"],
["Mario", "plumber", "married"]
]
for person_info in people:
print "Name:", person_info[0], "job:", person_info[1], "is", person_info[2]
在循环中解压缩嵌套项是恰当的:
for name, job, marital_status in people:
print "Person named", name, "works as a", job, "and is", marital_status