收集列表中的所有其他字符串/文件中的行 [英] Gathering every other string from list / line from file
问题描述
我已经编写了大约两个星期的脚本,并且刚刚学会了从文件中读取内容.
I have been scripting for around two weeks, and have just learnt about reading from a file.
我要做的是从原始列表中获取所有其他条目,并将其存储在新列表中.这是最好的方法吗?
What I want to do is get every other entry from my original list and store it in a new list. Is this the best way to do it?
with open("test.txt",mode="r") as myfile:
File = myfile.read().splitlines()
Username = []
for i in range (len(File)):
if File.index(File[i])%2 == 0 or File.index(File[i]) == 0:
Username.append(File[i])
print(Username)
请记住,到目前为止,我仅学习Python大约十个小时-我很高兴它甚至可以正常工作.
Please bear in mind that I have only studied Python for around ten hours so far - I'm quite happy that this even seemed to work.
推荐答案
至少有两种方法可以用更少的代码来完成同一件事.
There are at least a couple ways to accomplish the same thing with less code.
Python提供了一种遍历称为切片符号的数组的第n个元素的方法.您可以将整个循环替换为以下行
Python has a way of iterating over every nth element of an array called slice notation. You can replace the entire loop with the following line
Username.extend(File[0::2])
这基本上意味着从索引0
开始获取每个2
nd元素,并将其添加到Username
数组中.
What this basically means is to grab every 2
nd element starting at index 0
and add it to the Username
array.
您还可以使用range()
函数的其他版本,该函数允许您指定开始,结束和步骤,如此列出.
You can also use a different version of the range()
function, that allows you to specify a start, end and step, list so.
for i in range(0, len(File), 2):
Username.append(File[i])
在此处中记录了range()
函数.
这篇关于收集列表中的所有其他字符串/文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!