user10098871
user10098871

Reputation:

Python return specific items from list in same line

I have a list of items from which I need to separate items with specific "key". Let's say I need all items that follow "X" -> the list may look like this: Y1 1-2 X1 3-5 Z1 6-8, Y2 3-5 X2 5-7 Z2 5-9 so I need to take the X "values" that are 3-5 and 5-7. These should be returned this way: 3 4 5 and 5 6 7 and on their own lines so that they can be used in another functions.

I have also tried taking "X"s to its own dictionary but the problem is still the same. I also know about end="" but it does not help me with this.

def get_x_values(list_parameter):  

list_of_items = []
list_of_x = []

for i in list_parameter:
    i = i.split(' ')
    for item in i:
        if item != '':
            list_of_items.append(item)
for item, next_item in zip(list_of_items, list_of_items[1:]):
    if item == 'X':
        list_of_x.append(next_item)
for x in list_of_x:
    for i in range(int(x[0]), int(x[-1]) + 1):
       yield i

When I loop the yield values trough, I get the X values like this:

3
4
5
5
6
7 

When I need them this way:

3 4 5
5 6 7

Any help appreciated.

Upvotes: 0

Views: 771

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51683

You need to

  • split your list (you got it)
  • put key and value together (you use zip, I use a dict comprehension for that)
  • split your values into numbers and convert to int
  • create a range from your int-converted values to fill in missing numbers

for example like so:

# there is a pesky , in your string, we strip it out
inp = "Y1 1-2 X1 3-5 Z1 6-8, Y2 3-5 X2 5-7 Z2 5-9"

formatted_input = [a.rstrip(",") for a in inp.split(" ")]
print(formatted_input)

# put keys and values together and convert values to int-list
as_dict = {formatted_input[a]:list(map(int,formatted_input[a+1].split("-"))) 
           for a in range(0,len(formatted_input),2)}
print(as_dict)


# create correct ranges from int-list
as_dict_ranges = {key:list(range(a,b+1)) for key,(a,b) in as_dict.items()}
print(as_dict_ranges)

# you could put all the above in a function and yield the dict-items from here:
# yield from as_dict_ranges.item()  
# and filter them for key = X.... outside

# filter for keys that start with X
for k,v in as_dict_ranges.items():
    if k.startswith("X"):
        print(*v, sep=" ")   # decompose the values and print seperated onto one line

Outputs:

# formatted_input
['Y1', '1-2', 'X1', '3-5', 'Z1', '6-8', 'Y2', '3-5', 'X2', '5-7', 'Z2', '5-9']

# as_dict
{'Y1': [1, 2], 'X1': [3, 5], 'Z1': [6, 8], 
 'Y2': [3, 5], 'X2': [5, 7], 'Z2': [5, 9]}

# as_dict_ranges
{'Y1': [1, 2], 'X1': [3, 4, 5], 'Z1': [6, 7, 8], 
 'Y2': [3, 4, 5], 'X2': [5, 6, 7], 'Z2': [5, 6, 7, 8, 9]}

# output for keys X...
3 4 5
5 6 7

You can omit one list conversion if you do not want to print the map(int, ...) values:

as_dict = {formatted_input[a]:map(int,formatted_input[a+1].split("-")) 
           for a in range(0,len(formatted_input),2)}

Documentation:

Upvotes: 0

Train
Train

Reputation: 575

I modified you code, so that it will work.

def get_x_values(list_parameter): 
    list_of_items = []

    for i in list_parameter:
        i = i.split(' ')
        for item in i:
            if item != '':
                list_of_items.append(item)

    for item, next_item in zip(list_of_items, list_of_items[1:]):
        if item == 'X':
            range_list = list(range(int(next_item[0]), int(next_item[-1]) + 1))
            yield " ".join(str(number) for number in range_list)


lst = ["Y 1-2 X 3-5 Z 6-8", "Y 3-5 X 5-7 Z 5-9"]
result = get_x_values(lst)

for x in result:
    print(x)

However, this is not the most elegant solution. But I guess it's easier to understand for you as it's pretty close to your own attempt.

I hope it helps you. Let me know if there are any questions left. Have a nice day!

Upvotes: 1

Related Questions