我如何在列表中访问特定长度

发布于 2025-02-13 17:38:12 字数 633 浏览 0 评论 0原文

我正在阅读文本文件,我想在某个定界符之后访问信息我想要值ZOEbox

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏日落 2025-02-20 17:38:12
example = ["-t2=zoe", "-d2=box"]

使用循环标准,您只需在所有元素上循环,以=拆分,然后将右侧(索引1)附加到新列表中。通过使用split()函数,您将获得一个带有两个元素的数组 - 第一个元素包含所有字符,然后在选定的拆分字符和第二个字符之后的第二个字符。如果在之前或之后没有字符,则列表中的各个元素将为空(''

result = []
for element in example:
    result.append(element.split("=")[1])

,或者您可以使用列表理解来一行进行操作:

result_list_comprehension = [element.split("=")[1] for element in example]

或者如果您不希望要以特定的字符拆分,但仅以特定索引(在这种情况下为索引4):

result_list_comprehension_fixed_length = [element[4:] for element in example]
example = ["-t2=zoe", "-d2=box"]

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 the split() 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 ('')

result = []
for element in example:
    result.append(element.split("=")[1])

Or you can use a list comprehension to do this in one line:

result_list_comprehension = [element.split("=")[1] for element in example]

Or if you don't want to split at a specific character, but just at a specific index (in this case index 4):

result_list_comprehension_fixed_length = [element[4:] for element in example]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文