Jason Lee
Jason Lee

Reputation: 1

iterating through names by loop in python

I need to do repetitive coding for many years, for instance,

G1990 = pd.read_csv("map_1990.csv")
G1991 = pd.read_csv("map_1991.csv")
". . ."
G2015 = pd.read_csv("map_2015.csv")

Other examples are,

path2001=dict(nx.all_pairs_shortest_path_length(G2001))
path2002=dict(nx.all_pairs_shortest_path_length(G2002))
path2003=dict(nx.all_pairs_shortest_path_length(G2003))
". . . "
path2015=dict(nx.all_pairs_shortest_path_length(G2015))

and

df2001.to_csv("path2001.csv")
df2002.to_csv("path2002.csv")        
df2003.to_csv("path2003.csv")
". . . "
df2015.to_csv("path2015.csv")

it would be nice if I can use a loop to simplify my code, such that

for i in range(1990:2015),
    G[i] = pd.read_csv("map_[i].csv")

or

for i in range(2001:2015),
    path[i]=dict(nx.all_pairs_shortest_path_length(G[i]))

and

for i in range(1990:2015),
    df[i].to_csv("path[i].csv")

Help me please :)

Upvotes: 0

Views: 87

Answers (3)

Sunitha
Sunitha

Reputation: 12015

Yes. Of course you can do it as follow:

G = {}
for i in range(1990, 2016):
    G[i] = pd.read_csv(f"map_{i}.csv")

or, in short:

G = {i: pd.read_csv(f"map_{i}.csv") for i in range(1990, 2016)}

Upvotes: -1

mani k
mani k

Reputation: 1

g = {}


for i in range(1900,2015):    
        g[i] = pd.read_csv('map_'+ str(i) + '.csv')    

Upvotes: 0

abarnert
abarnert

Reputation: 365925

it would be nice if I can use a loop to simplify my code, such that

for i in range(1990:2015),
    G[i] = pd.read_csv("map_[i].csv")

Well now you can!

You just need to fix the syntax a bit.

  • : is for slices, not ranges; you need range(1990, 2015).
  • Ranges are "half-open", so range(1990, 2015) would not include 2015.
  • for statements, and all compound statements in Python, need a : at the end.
  • You have to create G before you can add things to it.
  • Python's format strings use {} rather than [].
  • Python's format strings have to be explicitly marked with f.1
  • Completely-meaningless single-letter variable names are a bad idea, even in completely-meaningless toy examples; they should instead be words taken from the Spam sketch. Otherwise you'll be sentenced to program in C++.

So:

eggs = {}
for i in range(1990, 2016):
    eggs[i] = pd.read_csv(f"map_{i}.csv")

1. If you're using Python 3.5 or earlier, including 2.7, you can't use f-strings; instead, you have to write "map_{}.csv".format(i).

Upvotes: 4

Related Questions