Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 List Comprehension - Creating a list of the length of an item help
#1
I am working within a file which is within a for loop. Within this for loop i am wanting to create a new list. I can do what i want using normal list way but was hoping to find out how to convert this into list comprehension. The complication to this is i am wanting to get the length of 'y' within the for loop captured into the new list.

Working way (long way):
NewList = []

for (x, y) in file:
    NewList.append(len(y))

print(NewList     
The above gives me what I want. However, I am hoping to make this more elegant and turn this into list comprehension. Anyone any ideas?

I have tried:
Newlist = [item for item in len(y)]
However, this does not work :-(. Thanks in advance.
Quote
#2
Do you mean this?
Newlist = [len(item[1]) for item in file]
Quote
#3
If you want turn your first code into list comprehension one-to-one you just write:

[len(y) for (x, y) in file]
In list comprehension what you get/want comes first. In spoken language: 'give me length of y for every x, y in file'
baquerik likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Topic: “Filter numbers with a list comprehension” (PyBite #107) Drone4four 4 182 Jun-11-2020, 08:31 PM
Last Post: Drone4four
  Creating a list of RSSI value and send it to the server. Azuan 0 110 Jun-08-2020, 11:22 PM
Last Post: Azuan
  converting list of zero length to a matrix of 3*3 vp1989 2 158 May-20-2020, 07:46 PM
Last Post: deanhystad
  Add items from one list to list of lists PUP280 5 586 May-05-2020, 03:47 PM
Last Post: PUP280
  Help: list comprehension for loop with double if statement mart79 3 193 May-04-2020, 06:34 AM
Last Post: buran
  best way to add item to list only once Phaze90 1 198 May-01-2020, 05:02 AM
Last Post: bowlofred
  Understand list comprehension and draw PUP280 9 488 Apr-23-2020, 05:25 PM
Last Post: PUP280
  item from a line to list however when i print the line instead of words i get letters Sutsro 5 212 Apr-22-2020, 02:39 PM
Last Post: deanhystad
  Help: List comprehension mart79 4 285 Apr-09-2020, 05:24 AM
Last Post: mart79
  Help removing asterisk item in a nested list. bmcguire 3 241 Apr-06-2020, 02:35 PM
Last Post: snippsat

Forum Jump:


Users browsing this thread: 1 Guest(s)