Rahul Ranjan
Rahul Ranjan

Reputation: 99

What is the way to delete words in Python list which does not have numbers?

 a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

the above list have words like history, members which do not have numbers in them, so i want to delete them

 # output would be
 a = ['in 1978 by', 'June 4th, 1979', 'October 7, 1986', 'In 1984 the', 'early 1990s; prominent']

Upvotes: 3

Views: 93

Answers (3)

John Lyon
John Lyon

Reputation: 11420

Using a regular expression and a list comprehension, this is a one-liner:

import re
[i for i in a if re.search('\d', i) is not None]

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

Here's a shorter alternative, using any() and string.digits:

from string import digits

a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 
     'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

[x for x in a if any(y in x for y in digits)]

=> ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge',
    'In 1984 the', 'early 1990s; prominent']

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142146

Keep the ones you want:

a = ['in 1978 by', 'History', 'members', 'albums', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

new = [el for el in a if any(ch.isdigit() for ch in el)]
# ['in 1978 by', 'June 4th, 1979', 'October 7,1986): "The Lounge', 'In 1984 the', 'early 1990s; prominent']

Upvotes: 8

Related Questions