简体   繁体   中英

Change Index of Two Python Lists Simultaneously

i'm using python 3, and have two lists that are related by their indices, but have separate values.

scans = [400,405]
points = [101,201]

So, for example, scan 400 has 101 points, and scan 405 has 201 points.

i'm trying to construct a set of filenames (ie strings) for each scan that looks like:

2idd_flyXMAP_0400_0.nc
2idd_flyXMAP_0400_1.nc
2idd_flyXMAP_0400_2.nc
...
2idd_flyXMAP_0400_98.nc
2idd_flyXMAP_0400_99.nc
2idd_flyXMAP_0400_100.nc

and

2idd_flyXMAP_0405_0.nc
2idd_flyXMAP_0405_1.nc
2idd_flyXMAP_0405_2.nc
...
2idd_flyXMAP_0405_199.nc
2idd_flyXMAP_0405_200.nc

Notice scan 405 will have more files associated with it. i got close with the the following code, but the nature of the nested for loop has me iterating too many times, and generating unwanted strings (ie a set for scan 400 containing 200 points, and a set for scan 405 containing 100 points, both are unnecessary).

scans = [400,405]
points = [101,201]

for scan in scans:
    pre_f = '2idd_flyXMAP_0' + str(scan) + '_'
    for point in points:
      endfile = list(range(point))  #this seems to be where the problem is; i generate four sets of lists here because i have two elements in two lists
      for point in endfile:
          f = pre_f  + str(point) + '.nc'
          print(f)

i may be setting this up inaccurately, but what i'd like to do in this case is change the index of both the scan for loop and the first point for loop once the first point for loop completes. i'm not sure how to accomplish this, but i think that should resolve my issue.

of course i'm open to separate, simpler approaches and thanks in advance for your help!

You could use zip :

scans = [400, 405]
points = [5, 6]

for scan, point in zip(scans, points):
    pre_f = '2idd_flyXMAP_0' + str(scan) + '_'
    for p in range(point):
        f = pre_f + str(p) + '.nc'
        print(f)

OUtput

2idd_flyXMAP_0400_0.nc
2idd_flyXMAP_0400_1.nc
2idd_flyXMAP_0400_2.nc
2idd_flyXMAP_0400_3.nc
2idd_flyXMAP_0400_4.nc
2idd_flyXMAP_0405_0.nc
2idd_flyXMAP_0405_1.nc
2idd_flyXMAP_0405_2.nc
2idd_flyXMAP_0405_3.nc
2idd_flyXMAP_0405_4.nc
2idd_flyXMAP_0405_5.nc

You could also use enumerate

for index, scan in enumerate(scans)
    for point in range(points[index])
        output = "{i}: {s}-{p}".format(i=index, s=scan, p=point)
        print(output)

You can use zip :

for point, scan in zip(points, scans):
   for p in range(point):
      print("2idd_flyXMAP_0{a}_{b}.nc".format(a=scan, b=p))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM