简体   繁体   中英

How do I check every element in an appended text in python

I am doing the Euler project questions and the question I am on right now is least common multiple. Now I can go the simple route and get the factors and then find the number that way, but I want to make my life hard.

This is the code I have so far in Python:

i = 0
j = 0
count = []
for i in range (1,10):
    for j in range(1,11):
        k = i%j
        count.append(k)
    print(count)

Now when I print this out I get an array and every time I goes through the loop, the previous information is appended on with it. How can I make it so that the previous information is not appended?

Second once I get that information how can I look at each value in the array and only print out those elements that are equal to 0? I feel like I have to use the all() function but for some reason I just dont get how to use it.

Any and all help is appreciated.

  1. For your first question, you should know the scope of variable. Just define the variable count inside the outer loop and before the inner loop starts.

  2. You can try this if you want nothing but zero elements.

    print [element for element in count if element == 0]

If I understand your question right the answer for your question is like this.

i = 0
j = 0

for i in range (1,10):

    # Resetting so that count will not have previous values
    count = []
    for j in range(1,11):
        k = i%j
        count.append(k)

    # printing all the indexes where the value is '0'
    print([index for index, item in enumerate(count) if item == 0])

You know your range of extern loop so you can just write your code in this way :

count = []
for i in range (1,10):
    for j in range(1,11):
      k = i%j
      if(i == 9):
        count.append(k)
print(count)
print("Without 0:")
print([x for x in count if x is not 0])

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