简体   繁体   中英

Python recursion with for loop

I want to process some files with Python and have below scripts:

import pandas as pd
loc1 = r'D:\1103\DC431.txt'
loc2 = r'D:\1103\DC432.txt'
loc3 = r'D:\1103\DC433.txt'
loc4 = r'D:\1103\DC434.txt'
loc5 = r'D:\1103\DC435.txt'
loc6 = r'D:\1103\DC436.txt'
loc7 = r'D:\1103\DC437.txt'
# Start
df1 = pd.read_table(loc1, sep=('\t'), engine='python')
df2 = pd.read_table(loc2, sep=('\t'), engine='python')
df3 = pd.read_table(loc3, sep=('\t'), engine='python')
df4 = pd.read_table(loc4, sep=('\t'), engine='python')
df5 = pd.read_table(loc5, sep=('\t'), engine='python')
df6 = pd.read_table(loc6, sep=('\t'), engine='python')
df7 = pd.read_table(loc7, sep=('\t'), engine='python')

s1 = df1[df1['No (Int)'] == 4]
s2 = df2[df2['No (Int)'] == 4]
s3 = df3[df3['No (Int)'] == 4]
s4 = df4[df4['No (Int)'] == 4]
s5 = df5[df5['No (Int)'] == 4]
s6 = df6[df6['No (Int)'] == 4]
s7 = df7[df7['No (Int)'] == 4]
# End

# Other scripts

I was trying to simplify the scripts between Start to End of the above using for loop, but python cannot identify:

for n in range (1,8):
    dfn = pd.read_table(locn, sep=('\t'), engine='python')
    sn = dfn[dfn['No (Int)'] == 4]

Anyone have good idears?

dfn and sn are variables names, python does not know that you mean an index n . You can use lists instead. First without list comprehension:

import pandas as pd

locs = []
dfs = []
ss = []

for i in range(1, 8):
    locs[i] = r'D:\1103\DC43{}.txt'.format(i)
    dfs[i] = pd.read_csv(locs[i], sep='\t')
    ss[i] = dfs[i][dfs[i]['No (Int)'] == 4

With list comprehension:

import pandas as pd

locs = [r'D:\1103\DC43{}.txt'.format(i) for i in range(1,8)]
dfs = [pd.read_csv(loc, sep='\t') for loc in locs]
ss = [df[df['No (Int)'] == 4] for df in dfs]

Note:

  • pandas.read_table is deprecated in favor of pandas.read_csv .
  • the C engine is probably enough, add the python engine back only if needed.

How about:

dict_result = dict()
for id in range(431, 438):
    loc = r'D:\1103\DC{0}.txt'.format(id)
    df = pd.read_table(loc, sep=('\t'), engine='python')
    s = df[df['No (Int)'] == 4]
    dict_result[id] = (loc, df, s)

You can use eval to get the value of variable Xn , and use exec to execute a statement. Here is a simple example:

a1 = 1
a2 = 2
b1 = {'1':{'w':1}, '2':2}
b2 = {'1':{'w':3}, '2':4}
for i in range(1,3):
    print(eval('a%d' % i))
    print(eval('b%d' % i)[str(i)])
exec('hello%d = 1234' % 99)
print(hello99)

The output is:

1
{'w': 1}
2
4
1234

Tested on Python3.4.9

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