[英]How do you print out a particular object in a given list?
So my program here is supposed to take in a sentence, and then spit out the third word. 因此,我在这里的程序应该采用一个句子,然后吐出第三个单词。
Here is my code below: 这是我的代码如下:
L = []
x = input('Enter a sentence: ')
L.append(x.split(' '))
print (L[2])
For some reason I get the error: IndexError: list index out of range
. 由于某种原因,我得到了错误: IndexError: list index out of range
。
If you actually print out the value of L
after you perform this: 如果执行此操作后实际打印出L
的值:
L.append(x.split(' '))
You will see you actually created a list of lists, which is definitely not what you want. 您将看到您实际上创建了一个列表列表,这绝对不是您想要的。 Running your code with a sample input "chicken bock", yields: 使用示例输入“ chicken bock”运行代码,将产生:
[['chicken', 'bock']]
What you want to do is simply assign the result of split
to L
您要做的只是将split
的结果split
给L
L = x.split(' ')
Furthermore, you need to pay attention as to how many elements you enter in your sentence. 此外,您需要注意句子中输入的元素数。 Especially since lists start at index 0, you need to make sure you actually access an index within the bounds. 特别是由于列表从索引0开始,因此您需要确保实际访问范围内的索引。 So if we take the example of "chicken bock" as input, your test of L[2]
, will not work. 因此,如果我们以“鸡博克”为例,则您对L[2]
测试将不起作用。 You would actually need L[1]
to get the second element of the list. 您实际上需要L[1]
才能获得列表的第二个元素。
Finally, if for whatever reason you are still looking to "add" elements to your list L
, then based on the solution you have worked out, you actually want to use extend
and not append
: 最后,如果出于任何原因您仍然希望将元素“添加”到列表L
,那么根据您已经解决的解决方案,您实际上想使用extend
而不是append
:
L.extend(x.split(' '))
A practical example that provides the third element: 一个提供第三个元素的实际示例:
L = []
x = input('Enter a sentence: ')
L = x.split(' ')
print(L[2])
Enter a sentence: chicken goes bock
bock
You are adding a list, created when you split the sentence, to a list. 您正在将拆分句子时创建的列表添加到列表中。 Thus, you have a final list with only one element, the list. 因此,您有一个仅包含一个元素的最终列表,即列表。 Try this: 尝试这个:
x = input('Enter a sentence: ')
l = []
l.extend(x.split())
print(new_list[2])
Try this: 尝试这个:
x = input("Enter a sentence:");
x.split(' ');
print (x[2])
string.split(x);
Will turn the output into an array, no need for using append. 将输出转换为数组,无需使用append。
If you want to append this value to an array now, just do array[a] = x[b]
, where a and b are integers. 如果要立即将此值附加到数组,只需执行array[a] = x[b]
,其中a和b是整数。
split() in python returns the list. python中的split()返回列表。 So you are just appending the list into your list L. Instead do L=x.split(' ')
因此,您只是将列表追加到列表L中。而是执行L=x.split(' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.