-1

I am new to python and working on a small project

NE = [ ("Maine", 30840, 1.329), ("Vermont", 9217, .626), ("New Hampshire", 8953,1.321), ("Massachusetts", 7800, 6.646), ("Connecticut", 4842, 3.59), ("Rhode Island", 1044, 1.05)]

where[0] is a state,[1] is land area,[2] is population

I have written the below code to sort in descending order of population

def s_sort(state):
    return state[2]

s_state = sorted(NE,key=s_sort,reverse=True)
print(s_state)

Output:

[('Vermont', 9217, 0.626), ('Rhode Island', 1044, 1.05), ('New Hampshire', 8953, 1.321), ('Maine', 30840, 1.329), ('Connecticut', 4842, 3.59), ('Massachusetts', 7800, 6.646)]

But how do I only return the name of the states from the above output in the same descending order within this function?

My desired output:

Vermont,Rhode Island,New Hampshire,Maine,Connecticut,Massachusetts

4 Answers4

1

You need to 'pluck' the first valueout of every tuple in the list you have. Python lacks an explicit pluck function, but you can use map.

st_state = map(lambda s: s[0], s_state)

(Or, yes, you can use a comprehension, as Fukiyel suggests.)

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
0

You can use a list comprehension :

print([el[0] for el in s_state])

["Vermont", "Rhode Island", "New Hampshire", "Maine", "Connecticut", "Massachusetts"]

More on list comprehension

(Or, yes, you can use the map built-in, as Malvolio suggests.)

Fukiyel
  • 1,166
  • 7
  • 19
  • How can I sort the list based on length of the name of state? –  Mar 06 '19 at 20:45
  • @user9991165 You can check this post : https://stackoverflow.com/questions/2587402/sorting-python-list-based-on-the-length-of-the-string – Fukiyel Mar 06 '19 at 20:47
0

Adding this line of code will do the trick

s = [i[0] for i in s_state]
Kay
  • 1
  • 1
0
state_names = []
for state in s_state:
    state_names.append(state[0])
return state_names   
darkcard
  • 15
  • 5