0

I have the following list:

ip= ['a boy called me z there', 'what u doing b over there ', "come w me t the end']

I want to remove all the single letters from each of these strings within the list.

I have tried the following but it does not work:

x = [[w for w in c if (len(w)>1)] for c in ip]

I want to convert my ip such that I get the following output op:

op= ['boy called me there', 'what doing over there ', "come me the end']
JodeCharger100
  • 903
  • 1
  • 12
  • 25

3 Answers3

7

When iterating ip by c, c becomes a char (e.g., 'a', ' ', 'b', 'o', 'y', ' ', ...)

So, try split each sentence by space and count the length.

Example code is here.

op = [' '.join([w for w in c.split(' ') if len(w) >= 2]) for c in ip]
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11
  • 1
    the `[]` in the join() isn't necessary here. (it will create a generator expression) – monkut May 18 '20 at 03:57
  • @monkut: `[]` makes it lil faster compared to generator expression. – Austin May 18 '20 at 04:01
  • 1
    @monkut `str.join` with generator is lower [check this answer from Raymond hettinger](https://stackoverflow.com/a/9061024/12416453). Using list is better option and faster. – Ch3steR May 18 '20 at 04:01
  • 1
    Interesting, learned something new here. Thanks @Ch3steR I wonder if anything has changed in the 8 years since that answer? I can't reproduce the timing diff. – Mark May 18 '20 at 04:06
  • Yes the list comp is faster (by ~ 1µs?), but if that's your issue it'd probably be a different question.with_generator_expression(): 4.27 µs ± 54.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) with_list_comprehension(): 3.39 µs ± 62.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) – monkut May 18 '20 at 04:17
  • @MarkMeyer Like monkut mentioned the list comprehension is faster by ~50-70 µs on my machine. Actually I commented on another post saying use generator [here](https://stackoverflow.com/questions/61811872/how-do-i-remove-subscript-superscript-in-python/61811945#comment109332035_61811945) then user2357112 supports Monica pointed out using list comp is better. – Ch3steR May 18 '20 at 04:35
1

try

for i in ip:
  p=i.split()
op=[]
for i in p:
  if(len(i)==1 ):
    op.append(i)
Sourhead
  • 15
  • 1
  • 5
1

I'd clean up the variable names for clarity, and you might want to break out the list comprehensions for readability, but either will function as expected.

sentences = ['a boy called me z there', 'what u doing b over there ', "come w me t the end"]
processed = [' '.join(word for word in sentence.split(' ') if len(word) > 1) for sentence in sentences]
monkut
  • 42,176
  • 24
  • 124
  • 155