2

I'm trying to create a program where the user inputs a list of strings, each one in a separate line. I want to be able to be able to return, for example, the third word in the second line. The input below would then return "blue".

input_string("""The cat in the hat 
Red fish blue fish """)

Currently I have this:

def input_string(input):
    words = input.split('\n')

So I can output a certain line using words[n], but how do output a specific word in a specific line? I've been trying to implement being able to type words[1][2] but my attempts at creating a multidimensional array have failed.

I've been trying to split each words[n] for a few hours now and google hasn't helped. I apologize if this is completely obvious, but I just started using Python a few days ago and am completely stuck.

4

4 回答 4

4

它很简单:

input_string = ("""The cat in the hat 
Red fish blue fish """)

words = [i.split(" ") for i in  input_string.split('\n')]

它生成:

[['The', 'cat', 'in', 'the', 'hat', ''], ['Red', 'fish', 'blue', 'fish', '']]
于 2013-07-18T19:34:26.373 回答
1

还有一种方法叫做splitlines()。它将在换行符上拆分。如果您不传递任何参数,它将删除换行符。如果你通过它True,它会保留在那里,但仍然分开行。

words = [line.split() for line in input_string.splitlines()]
于 2013-07-18T19:47:04.707 回答
1

听起来您想在os.linesep拆分空间之前拆分(当前操作系统的行分隔符)。就像是:

import os

def input_string(input)
   words = []
   for line in input.split(os.linesep):
       words.append(line.split())

这将为您提供每行的单词列表列表。

于 2013-07-18T19:34:13.257 回答
0

尝试这个:

lines = input.split('\n')
words = []
for line in lines:
    words.append(line.split(' '))

用英语讲:

  1. 构造一个行列表,这类似于从文件中读取。
  2. 循环遍历每一行,将其拆分为单词列表
  3. 将单词列表附加到另一个列表。这会产生一个列表列表。
于 2013-07-18T19:35:16.113 回答