Home > Net >  Python - list of tuples converted to string list
Python - list of tuples converted to string list

Time:06-14

I have a tuple list of university names and I'm trying to get it to store each university name as a string in a list. I have tried the following code. Any thoughts on how to achieve this?

def convertTuple(tup):
    str = ''
    for item in tup:
        str = str   item
    return str

main():

school = convertTuple(schoolName)

print(school)




schoolName = [('Carthage',), ('Clarkson',), ('F&M',), ('GMU',), ('Georgia_Tech',), ('IIT',), ('Kenyon',), ('MIT',), ('McDaniel',), ('Michigan_State',), ('NIU',), ('Oklahoma_State',), ('Penn_State',), ('Princeton',), ('Purdue',), ('Radford',), ('Ramapo',), ('Randolph_Macon',), ('Rowan',), ('Tarleton',), ('TCU',), ('Texas_State',), ('Tulane',), ('UMASS_Lowell',), ('University_Of_Alabama',), ('UC_Berkeley',), ('UC_Riverside',), ('Maine',), ('UMBC',), ('UNO',), ('South_Alabama',), ('South_Carolina',), ('UT_Austin',), ('Toronto',), ('University_Of_Washington',), ('Ursinus',), ('Washington_State',), ('Wisconsin',)]

CodePudding user response:

You're not accessing the elements in the tuples. The school name is item[0].

You're also concatenating the names into a string, not creating a list. Use a list comprehension to create a list.

def convertTuple(tuples: list) -> list:
    return [item[0] for item in tuples]

CodePudding user response:

you have to collect the string which is in the tuples

def convertTuple(tup):
    listOfSchoolName = []
    for item in tup:
        listOfSchoolName.append(item[0])

    return listOfSchoolName
schoolName = [('Carthage',), ('Clarkson',), ('F&M',), ('GMU',), ('Georgia_Tech',), ('IIT',), ('Kenyon',), ('MIT',), ('McDaniel',), ('Michigan_State',), ('NIU',), ('Oklahoma_State',), ('Penn_State',), ('Princeton',), ('Purdue',), ('Radford',), ('Ramapo',), ('Randolph_Macon',), ('Rowan',), ('Tarleton',), ('TCU',), ('Texas_State',), ('Tulane',), ('UMASS_Lowell',), ('University_Of_Alabama',), ('UC_Berkeley',), ('UC_Riverside',), ('Maine',), ('UMBC',), ('UNO',), ('South_Alabama',), ('South_Carolina',), ('UT_Austin',), ('Toronto',), ('University_Of_Washington',), ('Ursinus',), ('Washington_State',), ('Wisconsin',)]

school = convertTuple(schoolName)

print(school)

CodePudding user response:

The most Pythonic way to convert a list of tuples to a string is to use the built-in method str(...). If you want to customize the delimiter string, the most Pythonic way is to concatenate the join() method and the map() function '\n'.join(map(str, lst)) to convert all tuples to strings and gluing those together with the new-line delimiter '\n'.

lst = [(1,), (2,), (4,)]

# Method 1:
print(str(lst))

# Method 2: 
print('\n'.join(map(lambda x: str(x[0])   ' '   str(x[1]), lst)))

# Method 3:
print('\n'.join([str(x) for t in lst for x in t]))
  • Related