Reputation: 4195
Is there a way to skip the first iteration in this for-loop, so that I can put a for-loop inside a for-loop in order to compare the first element in the list with the rest of them.
from collections import Counter
vowelCounter = Counter()
vowelList = {'a','e','i','o','u'}
userString = input("Enter a string ")
displayed = False
for letter in userString:
letter = letter.lower()
if letter in vowelList:
vowelCounter[letter] +=1
for vowelCount1 in vowelCounter.items():
char, count = vowelCount1
for vowelCount2 in vowelCounter.items(STARTING AT 2)
char2, count2 = vowelCount2
if count > count2 : CONDITION
How would the syntax go for this? I only need to do a 5 deep For-loop. So the next would Start at 3, then start at 4, then 5, the the correct print statement depending on the condition. Thanks
Upvotes: 0
Views: 10669
Reputation: 5677
Slicing a list with [1:] as suggested by a few others creates a new array. It is faster and more economic to use a slice iterator with itertools.islice()
from itertools import islice
for car in islice(cars, 1, None):
# do something
Upvotes: 0
Reputation: 64
To skip an iteration you can use the continue
keyword eg:
list = [1,2,3,4,5,6,7,8,9,10]
for value in list:
if value == list[0]:
continue
print(value)
Would give you:
2
3
4
5
6
7
8
9
10
I hope this answers your question.
Upvotes: 2
Reputation: 54561
It looks like what you want is to compare each count to every other count. While you can do what you suggested, a more succinct way might be to use itertools.combinations
:
for v1,v2 in itertools.combinations(vowelCounter, 2):
if vowelCounter[v1] > vowelCounter[v2]:
# ...
This will iterate over all pairs of vowels for comparison. Doing it this way, you may also want to check if vowelCounter[v2] > vowelCounter[v1]
as you won't see these two again (this goes for this method or the nested for loop method). Or, you can use the itertools.permutations
function with the same arguments and just one check would suffice.
Upvotes: 2
Reputation: 122376
You could do:
for vowelCount2 in vowelCounter.items()[1:]:
This will give you all the elements of vowelCounter.items()
except the first one.
The [1:]
means you're slicing the list and it means: start at index 1
instead of at index 0
. As such you're excluding the first element from the list.
If you want the index to depend on the previous loop you can do:
for i, vowelCount1 in enumerate(vowelCounter.items()):
# ...
for vowelCount2 in vowelCounter.items()[i:]:
# ...
This means you're specifying i
as the starting index and it depends on the index of vowelCount1
. The function enumerate(mylist)
gives you an index and an element of the list each time as you're iterating over mylist
.
Upvotes: 4