如何修改数组值?

时间:2017-02-04 18:42:53

标签: python arrays python-2.7

我在将Linux技能转换为python时遇到了一些问题。任何指向正确方向的人都会非常感激。

概述

我有两个动态创建的列表;列表中的项目数可以根据许多不同因素而变化。 为了这个例子,我创建了2个静态列表来表示从其他地方(file_root和docs_directory)提取的数据:

def find_directory_function():
        global full_path
        file_root = ['/home/work'] #number of values here can change!
        # number of values below can change!
        docs_directory = ['important.docs/','random.directory/', dev.stuff/]
        PATH = []
        full_path=[]

        for i in docs_directory:
                PATH = file_root.join(i)
                full_path.append(PATH)
                print full_path

find_directory_function()

期望

我希望输出是另一个具有以下值的数组(full_path):

full_path = ["/home/work/important.docs/",
             "/home/work/random.directory/",
             "/home/work/dev.stuff/",]

问题

  1. 正在引发以下异常:

    Traceback (most recent call last):
      File "test.py", line 15, in <module>
        find_directory_function()
      File "test.py", line 11, in find_directory_function
        PATH = file_root.join(i)
    AttributeError: 'list' object has no attribute 'join'
    
  2. 即使我设法操纵字符串并将它们放在数组中,它们仍会在连接值的中间缺少“/”(斜杠)。

3 个答案:

答案 0 :(得分:0)

使用os.path.join

import os
import copy
def find_directory_function():
    global full_path
    file_root = ['/home/work'] #number of values here can change!
    docs_directory = ['important.docs/','random.directory/', dev.stuff/] #number of values here can change!
    PATH = []
    full_path=[]

    for i in docs_directory:
        # since file_root can be an array, use copy to grab a copy 
        # of the array
        args = copy.copy(file_root)
        # and stick `i` on the end of that array so
        # that we have our full param list for os.path.join
        args.append(i)
        PATH = os.path.join(*args)
        full_path.append(PATH)
        print full_path

find_directory_function()

答案 1 :(得分:0)

file_root = ['/home/work']更改为file_root = '/home/work/'

或在for循环中进行以下更改:

file_root[0] + "/" + i

答案 2 :(得分:-1)

怎么样

import os.path
# ...

def make_full_paths(roots, paths):
    "roots is a list of prefixes. paths is a list of suffixes."
    full_paths = []
    for root in roots:
        for path in paths:
            full_paths.append(os.path.join(root, path))
    return full_paths

还有其他方法可以做到......作为yield的生成器函数(可能不是你想要的,因为你可能想多次使用full_paths);或使用https://docs.python.org/2/library/itertools.html#itertools.product,这将使其成为一个单行(更高级):

import itertools
import os.path
# ...

def make_full_paths2(roots, paths):
    "roots is a list of prefixes. paths is a list of suffixes."
    return [os.path.join(root, path) for root, path in itertools.product(roots, paths)]