[英]iterating each string of sentences in a list at a time in python using one line for loop
I have a list of strings of sentences like the following:我有一个句子字符串列表,如下所示:
my_list= ["my name is X", "the house is far", "the place is cold"]
what I would like to do is to basically access one sentence as a string from this list each time using a for loop in one line.我想做的基本上是每次在一行中使用for循环从这个列表中访问一个句子作为字符串。
I have tried:我努力了:
sent = [[l for l in sen] for sen in my_list]
but it returns a list of lists of character strings.但它返回字符串列表的列表。
so what i want is to access the sentences as strings one at a time with a one line for loop.所以我想要的是用一行for循环一次一个地访问句子作为字符串。
You don't need a nested comprehension for this.您不需要对此进行嵌套理解。 You can just use a single list comprehension:
您可以只使用一个列表推导:
sent = [do_something(sen) for sen in my_list]
Or with a normal for loop, if you don't have a need to make a new list:或者使用普通的 for 循环,如果您不需要创建新列表:
for sen in my_list:
do_something(sen)
The latter can also be done in one physical line:后者也可以在一条物理线路中完成:
my_list= ["my name is X", "the house is far", "the place is cold"]
for sen in my_list: print(sen)
Output:
Output:
my name is X the house is far the place is cold
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.