【问题标题】:Creating an array out of another array between 2 elements从两个元素之间的另一个数组中创建一个数组
【发布时间】:2018-10-02 22:15:22
【问题描述】:

我正在使用 readlines() 在 python 中读取文件

lines = f.readlines()

如何将所有组件添加到出现在 2 个特定字符之间的行中,例如:

lines = [rose, 1 , 2 , 4 , 5, 6], garden, plants ]

我想创建一个数组,这样:

array = [1,2,3,4,5,6]

我该怎么做?

【问题讨论】:

  • 自己尝试。如果您有具体问题,请出示您的代码并提问。
  • 在 StackOverflow,我们正在帮助开发人员变得更强大。但是,我们永远不会让公司通过在这个论坛上请求免费工作来摆脱它们。因此,为了将自己与这些鲨鱼区分开来,请向我们展示一些努力、一些代码、一些错误等等......然后我们会帮助你!
  • 整个“data:”+数组是不是一行?
  • 是的,都在同一行
  • 更改了问题@JonathanGagne

标签: python arrays file readfile texas-instruments


【解决方案1】:
#Read File
file = open("testFile.txt", "r")
f_str=file.read()
# Find positions of  [] in String
begin_pos= f_str.find('[')+1
end_pos= f_str.find(']')
# Get Subset of String and Split it by ',' in a Str List
f_str=f_str[begin_pos:end_pos].split(',')
#Str List to Int List
plist=list(map(int, f_str))
#Test it
print(plist)
print(type(plist[1]))

【讨论】:

    【解决方案2】:

    以下应该会有所帮助:

    # Open File
    with open('../input_file.txt') as f:
        lines = f.readlines()
    
    # Find the required attribute
    for line in lines:
        if line[:4] == 'data':
            data = line.split(':')[1].strip()
            break
    
    # Split the content to make a list of INTEGERS
    python_list = map(lambda x : int(x.strip()),data[1:-1].split(','))
    

    它提供了一个整数列表,因为数据是数字的。谢谢。

    【讨论】:

      【解决方案3】:

      试试这个:

      with open('Path/to/file', 'r') as f:
          content = f.readlines()
          data = content[8][7:].split(",")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-02
        • 1970-01-01
        • 1970-01-01
        • 2019-06-27
        • 2022-01-03
        • 2022-11-17
        • 1970-01-01
        • 2021-10-16
        相关资源
        最近更新 更多