如何在Python中处理中断数组? [英] How to process break an array in Python?
问题描述
我想使用双精度数组.但是我仍然做不到.这就是我所做的.
I would like to use a double array. But I still fail to do it. This what I did.
Folder = "D:\folder"
Name = ['gadfg5', '546sfdgh']
Ver = [None, 'hhdt5463']
for dn in Name :
for dr in Ver :
if dr is None:
Default = "asbsda"
Path = os.path.join(Folder, Default)
print(Path)
else:
Path = os.path.join(Folder, dr, dn)
print(Path)
它返回此:
D:\folder\gadfg5\asbsda
D:\folder\gadfg5\asbsda
D:\folder\gadfg5\asbsda
D:\folder\546sfdgh\hhdt5463
但是我对输出的期望是:
But my expectation of the output is:
D:\folder\gadfg5\asbsda
D:\folder\546sfdgh\hhdt5463
任何人都可以给我建议或想法.谢谢.
Anyone can give me advice or idea please. Thank you.
推荐答案
您发布的代码输出为:
D:\Folder\asbsda
D:\Folder\hhdt5463\gadfg5
D:\Folder\asbsda
D:\Folder\hhdt5463\546sfdgh
这是可以预期的,因为您要遍历两个数组,每个数组都有2个元素,并给出4种组合:
it is expected because you iterate through both arrays that has 2 elements each and that gives 4 combinations:
gadfg5&没有
gadfg5&hhdt5463
546sfdgh&没有
546sfdgh&hhdt5463
希望您能理解
要获得所需的结果,请尝试使用zip:
To get the desired result try using zip:
Folder = "D:\Folder"
Name = ['gadfg5', '546sfdgh']
Ver = [None, 'hhdt5463']
for dn, dr in zip(Name, Ver): # get each element of Name and Ver in sequence
if dr is None:
Default = "asbsda"
Path = os.path.join(Folder, dn, Default)
print(Path)
else:
Path = os.path.join(Folder, dn, dr)
print(Path)
Zip将每个数组的每个元素组合成一个元组,并返回一个元组数组以迭代遍历 zip([a,b,c],[1,2,3])->[(a,1),(b,2),(c,3)]
Zip combines each element of each of the array to a tuple and return an array of tuples to iterate through, zip([a,b,c], [1,2,3]) -> [(a,1),(b,2),(c,3)]
或枚举:
Folder = "D:\Folder"
Name = ['gadfg5', '546sfdgh']
Ver = [None, 'hhdt5463']
for idx, dn in enumerate(Name): # get index and element of Name
if Ver[idx] is None:
Default = "asbsda"
Path = os.path.join(Folder, dn, Default)
print(Path)
else:
Path = os.path.join(Folder, dn, Ver[idx])
print(Path)
enumerate为可迭代对象添加一个计数器,并为数组的每个元素提供索引.
enumerate adds a counter to your iterable and gives you each element of the array with its index.
输出:
D:\Folder\gadfg5\asbsda
D:\Folder\546sfdgh\hhdt5463
这篇关于如何在Python中处理中断数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!