I have a path: orders/line/2/codes/code/4/value
and I need to create a list where I need to multiply the path based on number values within the path:
from this: orders/line/2/codes/code/4/value
to this:
[orders/line/1/codes/code/1/value,
orders/line/1/codes/code/2/value,
orders/line/1/codes/code/3/value,
orders/line/1/codes/code/4/value,
orders/line/2/codes/code/1/value,
orders/line/2/codes/code/2/value,
orders/line/2/codes/code/3/value,
orders/line/2/codes/code/4/value]
how could I achieve this the most efficient way?
The number of number values are changing each time, like: orders/line/2/codes/code/4/values/value/5/kg
or even more tag.
CodePudding user response:
from pprint import pprint
result = []
for i in range(1,3):
for j in range(1,5):
result.append(f'orders/line/{i}/codes/code/{j}/value')
pprint(result)
CodePudding user response:
I've used f-string to modify the numbers
final=[]
for base in range(1,3):
for inner in range(1,5):
final.append(f"orders/line/{base}/codes/code/{inner}/value")
for i in final:
print(i)
Outputs
orders/line/1/codes/code/1/value
orders/line/1/codes/code/2/value
orders/line/1/codes/code/3/value
orders/line/1/codes/code/4/value
orders/line/2/codes/code/1/value
orders/line/2/codes/code/2/value
orders/line/2/codes/code/3/value
orders/line/2/codes/code/4/value
CodePudding user response:
path = 'orders/line/2/codes/code/4/value'
vals = path.split('/')
for i in range(int(vals[2])):
for j in range(int(vals[5])):
print( os.path.join(vals[0],vals[1],str(i 1),vals[3],vals[4],str(j 1),vals[6]) )
Output:
orders/line/1/codes/code/1/value
orders/line/1/codes/code/2/value
orders/line/1/codes/code/3/value
orders/line/1/codes/code/4/value
orders/line/2/codes/code/1/value
orders/line/2/codes/code/2/value
orders/line/2/codes/code/3/value
orders/line/2/codes/code/4/value
CodePudding user response:
Using a f-string and a list comprehension is pretty efficient;
paths = [f'orders/line/{i}/codes/code/{j}/value' for i in range(1,3) for j in range(1,5)]
CodePudding user response:
You can use itertools.product
to generate the desired combinations of upperbounds for range
objects:
from itertools import product
template = 'orders/line/{}/codes/code/{}/values/value/{}/kg'
numbers = [2, 4, 5]
print([template.format(*p) for p in product(*(range(1, i 1) for i in numbers))])
Demo: https://replit.com/@blhsing/AuthenticSeashellGigahertz