Reputation: 372
I have write python code and it has too many for loop, as a result, my code readability is too low and pylint star too low.
I am finding a way to solve same with fewer line of code.
here you go for my snippet:
numberlist = [1,3,5]
stringlist = ['a', 'b', 'c']
id = '458'
numbered_string = []
for n, s in numberlist, stringlist:
num_str = "{}{}".format(
n,
s,
id,
)
numbered_string.append(num_str)
codes = []
for n,s, sn in numberlist, stringlist, numbered_string:
code = make_code(
n,
s,
sn
)
codes.append(code)
print(codes)
Ignore the function make_code()
, or let's assume the make_code()
is
def make_code(n,s, sn):
return str(n) + str(s) + str(sn)
Can anyone help me shorten the snippet?, please ignore the function. I want to improve this code much better and high readability, too many instance is not a solution.
Upvotes: 0
Views: 65
Reputation: 151
Take a look at list comprehensions. So, instead of:
codes = []
for n, s, sn in zip(numberlist, stringlist, numbered_string):
code = make_code(
n,
s,
sn
)
codes.append(code)
you can write:
codes = [make_code(n, x, sn) for n, x, sn in zip(numberlist, stringlist, numbered_string)]
Note that I used zip(numberlist, stringlist, numbered_string)
in the for
statement instead of the bare numberlist, stringlist, numbered_string
. At least for me, on python 3.6, the latter does not work.
List comprehensions (and relatives for sets, dictionaries, generators, etc.) are super useful, and have lots of features, such as filtering using an if
clause after the for
clause, and supporting nested loops.
If your goal is to improve the readability of your code, you might want to also make sure your spacing is consistent (e.g. n, s, sn
instead of n,s, sn
) and your naming of variables is consistent -- in general, in python, variables and functions should be written in snake_case
(e.g. number_list
instead of numberlist
).
Upvotes: 6