0

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.

1
  • Hi there. Could you provide an example of what you expect numbered_string to contain? Because as is, your code gives an error at for n, s in numberlist, stringlist: (should be zipped?) Commented Aug 7, 2019 at 3:59

1 Answer 1

6

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.