I think you need to process each item in the list as a split string on whitespace.
a = ['1 2 3', '4 5 6', 'invalid']
numbers = []
for item in a:
for subitem in item.split():
if(subitem.isdigit()):
numbers.append(subitem)
print(numbers)
['1', '2', '3', '4', '5', '6']
Or in a neat and tidy comprehension:
[item for subitem in a for item in subitem.split() if item.isdigit()]
Answer from paleolimbot on Stack OverflowI think you need to process each item in the list as a split string on whitespace.
a = ['1 2 3', '4 5 6', 'invalid']
numbers = []
for item in a:
for subitem in item.split():
if(subitem.isdigit()):
numbers.append(subitem)
print(numbers)
['1', '2', '3', '4', '5', '6']
Or in a neat and tidy comprehension:
[item for subitem in a for item in subitem.split() if item.isdigit()]
That should do for your particular case since you include a string within list. Therefore you need to flatten it:
new_list = [int(item) for sublist in a for item in sublist if item.isdigit()]
How to extracts number from this python list
How to extract numbers from a string in Python? - Stack Overflow
extracting numbers from list of strings with python - Stack Overflow
Extract numbers from a string list - python - Stack Overflow
My list =[ ' 14,200 new items ' , '15,200 new items '] I tried for loop with isdigit to extract number But output was blank list .
I'd use a regexp:
>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']
This would also match 42 from bla42bla. If you only want numbers delimited by word boundaries (space, period, comma), you can use \b:
>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']
To end up with a list of numbers instead of a list of strings:
>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]
NOTE: this does not work for negative integers
If you only want to extract only positive integers, try the following:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.
You can use id\s(\d{7}) regular expression.
Iterate over items in a list and join the results of findall() call by ;:
import re
lst1 = [
'(Tower 3rd floor window corner_ : option 3_floor cut out_large : GA - floors : : model lines : id 3999595(tower 4rd floor window corner : option 3_floor: : whatever else is in iit " new floor : id 3999999)',
'(Tower 3rd floor window corner_ : option 3_floor cut out_large : GA - floors : : model lines : id 3998895(tower 4rd floor window corner : option 3_floor: : id 5555456 whatever else is in iit " new floor : id 3998899)'
]
pattern = re.compile(r'id\s(\d{7})')
print ["; ".join(pattern.findall(item)) for item in lst1]
prints:
['3999595; 3999999', '3998895; 5555456; 3998899']
Based on @alecxe solution you can also do it without any imports.
If your id numbers are always after id and have a fixed (7) number of digits I would probably just use .split('id ') to separate it and get the 7 digits from the second block onwards.
You can put them together in the desired format by using '; '.join()
Putting everything together:
pattern = ['; '.join([value[:7] for value in valueList.split('id ')[1:]]) for valueList in lst1]
Which prints out:
['3999595; 3999999', '3998895; 5555456; 3998899']
x = [ [100] , [500] , [300] ]
y = [ i[0] for i in x]
#or
from itertools import chain
y = list(chain.from_iterable(x))
From this question:
l=[[100], [500], [300]]
result=[item for sublist in l for item in sublist]
From wikibooks:
def flatten(seq, list = None):
"""flatten(seq, list = None) -> list
Return a flat version of the iterator `seq` appended to `list`
"""
if list == None:
list = []
try: # Can `seq` be iterated over?
for item in seq: # If so then iterate over `seq`
flatten(item, list) # and make the same check on each item.
except TypeError: # If seq isn't iterable
list.append(seq) # append it to the new list.
return list
Google is your friend ...
There are several points here:
- Use
re.searchsincere.matchonly searches for the match at the string start, - Escape the dot as it is a special regex metacharacter
- You filter the list only with
filter(...), you do not extract the values. - If you plan to find the
digit+.digit+first occurrence you may use a regex like\d+\.\d+ - If your items are all in the
string numberformat uses.split()[-1]to get the number, no need for a regex
Use
dat_list = [float(dat_re.search(x).group()) for x in l if dat_re.search(x)]
Or, if the format is fixed
dat_list = [float(x.split()[-1]) for x in l]
See the Python demo:
import re
l = ['string 23.3', 'NumberDescription 33.35']
dat_re = re.compile(r'\d+\.\d+')
dat_list = [float(dat_re.search(x).group()) for x in l if dat_re.search(x)]
print(dat_list)
# => [23.3, 33.35]
print([float(x.split()[-1]) for x in l])
# => [23.3, 33.35]
list_strings=['1','2','3']
for i in list_strings:
num_list.append(int(i))
or
list_num = [int(x) for x in list_strings]
Check this sample code once.
You forgot to use return list_of_numbers. You can also use a comprehension:
def abc(lst):
return [int(i) for i in lst if i.isdigit()]
abc(list00)
Output:
[90, 55, 100]
You don't have return in your function. Also i[0] is not good in this context, as it will give you the 0th character from the string, so for 90 you'd get only 9 as an int, not 90...
from typing import List
items = ["90", "hello", "55", "Hi", "100"]
def extract_numbers(items: List[str])->List[int]:
numbers = []
for item in items:
try:
numbers.append(int(item))
except Exception:
print("Skipping an item which cannot be casted to an int!")
return numbers
numbers = extract_numbers(items)
print(numbers)
Side notes:
- give variables (and functions) meaningful names
- use type hints when possible (it will help later on)
- do not use reserved keywords as names, not ever (e.g.
list,dict,tupleetc. is always a bad name) returnfrom a function if you need its output- in general do NOT silently
passon exception, do some logging or at least aprint
As for "why was the actual output none":
By default function with no explicit return statement (or with return, but no variable returned) returns None.
Give it a try:
def foo():pass
x = foo()
print(x) # It's gonna be None
def bar():
return
y = bar()
print(y) # The same here