简体   繁体   中英

How to subtract the minimum value from an indexed value of a list?

So I have a list , well a tuple now, that i want to subtract the calculated minimum for each value in the list/tuple. I used enumerate() to set a counter but I'm not sure if this is the best way to go. All I know is that I can't straight up subtract a list from a list. So any help would be great, sorry I'm a newbie.

I've tried map() to apply a function to each iterable

map(set(tuple) - set(minimum))

original_list = [['str1',2.33,7.46, 0.499],['str2', 45.55,4.77,6.22]]
tuple = [1, ('str1', 7.46,9.37,9.54,9.03,10.7)]
[2, ('str2', 2.46,9.37,9.54,9.03,10.7)]
min():
  columns = list(zip(*file))
  minimum = [min(list(x for x in column[1:] if x is not None)) for column in 
  columns

  # minimum = [7.46, 2.46]

where minimum is generated from a function

a = tuple - minimum

theoretically 1, x1, x2, x3 need to subtract minimum 7.46 then 2, x1, x2, x3 need to subtract 2.46 or min2 in minimum list.

in other words, is there a way that I can do something like this but with another list?

for i in range(len(tuple)):
  tuple[i] -= corresponding minimum value from minimum()

You can use a list comprehension:

data = ('str1', 7.46,9.37,9.54,9.03,10.7)
l = [x - min(data[1:]) if type(x) == float else x for x in data] #substract minimum from x if x is a float, else leave x as it is

However, the type stuff makes it a bit ugly. Maybe, if the data always look like [ "str", float, float, float, ...] you can do something like this:

data = list(data)
minimum = min(data[1:])
l = data[:1] + [x - minimum for x in data[1:]] #leave data[0] as it is, but substract minimum from each x of data[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