我如何在列表中访问特定长度
我正在阅读文本文件,我想在某个定界符之后访问信息我想要值ZOE
和box
。
def Unlock(file):
inp = input("1: Command Line or 2: Log File ")
if inp == "1":
print("You chose cmd line")
with open(file) as f:
lines = f.readlines()
new = ""
if(len(lines) == 1):
new = lines[0]
new = new.replace('-t', '!-t')
new = new.split('!')
else:
new = lines
for i in range(1,len(new)):
if '-t' in new[i]:
print(new[i])
I am reading in a text file and I want to access the information after a certain delimiter for example I'll have ["-t2=zoe", "-d2= box"]
as a list and I want the values zoe
and box
.
def Unlock(file):
inp = input("1: Command Line or 2: Log File ")
if inp == "1":
print("You chose cmd line")
with open(file) as f:
lines = f.readlines()
new = ""
if(len(lines) == 1):
new = lines[0]
new = new.replace('-t', '!-t')
new = new.split('!')
else:
new = lines
for i in range(1,len(new)):
if '-t' in new[i]:
print(new[i])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用循环标准,您只需在所有元素上循环,以
=
拆分,然后将右侧(索引1)附加到新列表中。通过使用split()
函数,您将获得一个带有两个元素的数组 - 第一个元素包含所有字符,然后在选定的拆分字符和第二个字符之后的第二个字符。如果在之前或之后没有字符,则列表中的各个元素将为空(''
),或者您可以使用列表理解来一行进行操作:
或者如果您不希望要以特定的字符拆分,但仅以特定索引(在这种情况下为索引
4
):With a standard for loop you can just loop over all the elements, split at
=
and append the right side (index 1) to a new list. By using thesplit()
function you will get an array with two elements - the first element contains all the characters before the chosen split character and the second the characters after the split character. If there are no characters before or after, the respective element in the list will be empty (''
)Or you can use a list comprehension to do this in one line:
Or if you don't want to split at a specific character, but just at a specific index (in this case index
4
):