I have a list containing a group of numbers ( str
) , and I want to check if there is at least one element in the list starting with '+'
.
The problem with my code is that an infinite loop will occur if no number starts with '+'
, I need a better solution?
my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
while True:
for number in my_list:
if number.startswith('+'):
break
my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
for number in my_list:
if number.startswith('+'):
break
This:
while True:
is unnecessary, the for loop will already check every item in the list
To make it clearer, if it print every iteration:
my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
for number in my_list:
print(number)
if number.startswith('+'):
break
I get
11112352
222222003
5682052003
21543003
98756003
+004454883
so as you can see the while loop is unnecessary
Here's a simpler solution:
my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
result = [x for x in my_list if x.startswith('+')]
if result:
# do something if result is not empty
else:
# result is empty -- no '+' entries in my_list
If you just need a True
/ False
result, you can try this:
any(number for number in my_list if number[0] == "+")
Function any delivers True
if at least one element of the list passed as argument is True
.
Edited as suggested by Ann Zen . See also How exactly any works
To check if any element starts with a '+'
, use builtin functions any
and str.startswith
. You can nearly write down the exact words as Python code:
starts_with_plus = any(element.startswith('+') for element in my_list)
This will return a boolean value. This will also return on the first instance where the condition is True
, like returning out of a loop, making this very efficient.
If you want to check for other prefixes as well, just put it in a small function:
def starts_with(lst, prefix):
return any(element.startswith(prefix) for element in lst)
starts_with_plus = starts_with(my_list, '+')
Use the any
method:
my_list = ['11112352', '222222003', '5682052003', '21543003', '98756003', '+004454883']
print(any(s[0] == '+' for s in my_list))
Output:
True
You can do this with the help of a for
loop and a flag
variable:
flag = 0
for item in my_list:
if item.startswith('+'):
flag = 1
break
print(flag)
If you get an output of 0
, then it's obvious that no element starts with a +
. On the other hand, if the output of the print statement is 1
, there's at least one element that starts with a +
.
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.