Skip to content Skip to sidebar Skip to footer

How Do I Print Values Of List?

I have a python question: Suppose you are given a vector, x, containing real values that are mostly zero. For instance: x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0

Solution 1:

You can define this function as follows:

defcompress_vector(x):
    d = {'inds': [], 'vals': []}

    for i, e inenumerate(x):
        if e != 0:
            d['inds'].append(i)
            d['vals'].append(e)
    return d

Basically, you create a dict which values for 'inds' and 'vals' are initialized to the empty list. Then, you iterate the list using enumerate in order to have the index (i) and the element (e). Inside the loop, you put the condition that the element should non-zero, and append i and e to the previous lists.

Solution 2:

You are very close. Let's look at one part of your code:

i, e in enumerate(x)

Here e is the value from the list x and i is the index. So you can modify the list comprehension to

[e for i, e in enumerate(x) if e != 0]
 ^

Note that since this doesn't need the index, you can get rid of the enumerate() call:

[e for e in x if e != 0]

You still need to make some modifications to store the two lists into a dictionary.

Solution 3:

Filter out the zeroes from an enumerated x and then use a dict-comprehension to extract the two elements from each tuple.

defcompress_vector(x):
    enumed = [(i,n) for i,n inenumerate(x) if n]
    return {k:[e[i] for e in enumed] for i,k inenumerate(('inds','vals'))}

and a test:

>>> compress_vector(x)
{'inds': [1, 5, 6, 9], 'vals': [0.87, 0.32, 0.46, 0.1]}

Solution 4:

This worked for me.

x = [0.0, 0.87, 0.0, 0.0, 0.0, 0.32, 0.46, 0.0, 0.0, 0.10, 0.0, 0.0]

def compress_vector(x):
    d = {'inds': [], 'vals': []}
    for i, valin enumerate(x):
        ifval != 0.0:
            d['inds'].append(i)
            d['vals'].append(val)

    return d

d = compress_vector(x)

Solution 5:

What you are doing here is that you are assigning a tuple object to the dictionary object. Notice:

d = ([i for i, e in enumerate(x) if e != 0], )

The enclosing braces for the list comprehension make it a tuple. So you can't getd to have this required represention:

d['inds'] = [1, 5, 6, 9]
d['vals'] = [0.87, 0.32, 0.46, 0.10]

You must explicitly append the values that satisfy the criteria to lists.

defcompress_vector(x):
    d = dict()
    d['inds'] = []
    d['vals'] = []
    for i, e inenumerate(x):
        if e != 0:
            d['inds'].append(i)
            d['vals'].append(e)
    return d

If there are no non-zero values they won't be appended to the lists and you will get a dictionary with empty lists.

Post a Comment for "How Do I Print Values Of List?"