Python 如何修改数组值?
我在将Linux技能转换为python时遇到了一些问题。任何指向正确方向的指针都将不胜感激 概述 我有两个动态创建的列表;列表中的项目数量可能会根据许多不同的因素而变化。 在本例中,我创建了两个静态列表来表示从其他地方(文件根目录和文档目录)提取的数据: 期望值 我希望输出是具有以下值的另一个数组(完整路径):Python 如何修改数组值?,python,arrays,python-2.7,Python,Arrays,Python 2.7,我在将Linux技能转换为python时遇到了一些问题。任何指向正确方向的指针都将不胜感激 概述 我有两个动态创建的列表;列表中的项目数量可能会根据许多不同的因素而变化。 在本例中,我创建了两个静态列表来表示从其他地方(文件根目录和文档目录)提取的数据: 期望值 我希望输出是具有以下值的另一个数组(完整路径): full_path = ["/home/work/important.docs/", "/home/work/random.directory/",
full_path = ["/home/work/important.docs/",
"/home/work/random.directory/",
"/home/work/dev.stuff/",]
问题
回溯(最近一次呼叫最后一次):
文件“test.py”,第15行,在
查找目录函数()
文件“test.py”,第11行,在find_directory_函数中
路径=文件\根.join(i)
AttributeError:“list”对象没有属性“join”
使用
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()
怎么样
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
的生成器函数(可能不是您想要的,因为您可能希望多次使用完整路径);或与,这将使它成为一个单班轮(更先进):
将
文件\u root=['/home/work']
更改为文件\u root='/home/work/'
或者在for
循环中执行以下更改:
file_root[0] + "/" + i
如果
file\u root
是一个列表,如何将文件与目录连接起来?用一个组合?产品?请尝试os.path.join(root,i)
,文件根应该是字符串,而不是字符串列表。我从您的评论中假设文件根目录的数量可以更改。对吗?如果是这样的话,请看我的答案。这非常有效!非常感谢。我还不能投票,但这正是我需要的!
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)]
file_root[0] + "/" + i