简体   繁体   中英

Only last list element returned in a variable

So I have a list of strings with some metric units inside. For example:

list=['i','am','160','cm','but','i','would','like','to','be','1.8','m']

I want to convert it into a new list, with the values converted through a dictionary. I'm making a variable of the metric units on the list, so that I can use it later for the conversion. But every time I call this variable only the last element is returned. (eg only the m in the list above).

Do you know how I can fix this?

SI_1 = {'mm':0.001, 'cm':0.01, 'm':1.0, 'km':1000}
for i in new_list:
    if i in SI_1:
        METRIC_IN_TEXT=i
        print(METRIC_IN_TEXT)
        METRIC_IN_TEXT_VALUE=SI_1.get(i)
        print(METRIC_IN_TEXT_VALUE)

I'm not sure what are you asking for, but we can convert all values from list using mapping this way:

  1. don't call variable list because it is build-in keyword.

Code example:

my_list=['i','am','160','cm','but','i','would','like','to','be','1.8','m']
mapper = {'mm':0.001, 'cm':0.01, 'm':1.0, 'km':1000}

res = [mapper[el] if el in mapper.keys() else el for el in my_list ]
res

output:

['i', 'am', '160', 0.01, 'but', 'i', 'would', 'like', 'to', 'be', '1.8', 1.0]

Sorry i wasn't clear at all on my post, because it is a uni assignment. SO i want to make a function that converts units from a text file, and then it writes the same text to a different file with the units converted. The target unit is determined by the DICT. SO my problem is that the list comprehension 'CONVERTED_LIST_1' generates different list for every conversion istead of one list with all the conversion. Hope i became more clear now

SI_1 = {'mm':0.001, 'cm':0.01, 'm':1.0, 'km':1000}
METRIC_IN_DICT=D.get('SIZE')
METRIC_IN_DICT_VALUE=SI_1.get(METRIC_IN_DICT)


with open('TEXT1.txt','r') as x:
        LIST=x.read().split()
        new_list=[item.replace('.','') if '.' in item else item for item in LIST]  
        for i in new_list:
            if i in SI_1:
            METRIC_IN_TEXT=i
            print(METRIC_IN_TEXT)
            METRIC_IN_TEXT_VALUE=SI_1.get(i)
            print(METRIC_IN_TEXT_VALUE)
            POS_OF_VALUE=new_list[new_list.index(METRIC_IN_TEXT)-1]
            print(POS_OF_LENGTH)
            RESULT=int(POS_OF_VALUE)*METRIC_IN_TEXT_VALUE/METRIC_IN_DICT_VALUE
            print(RESULT)   
            CONVERTED_LIST_1=[RESULT if i==POS_OF_VALUE and POS_OF_VALUE.isdigit() else METRIC_IN_DICT if i==METRIC_IN_TEXT else i for i in new_list] 
            print(CONVERTED_LIST_1)```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM