简体   繁体   中英

How to find a specific string in a python list, if found print the positions else print 0

input_String = str(input()) # Input is comma separated word
cargo_status = str(input()) # String to look into input string

list = input_String.split(",")
i = 0
length = len(list)
print(length)
for x in list:
    if x == cargo_status:
        i=i+1
        print(i)
    elif (not cargo_status in x) and (i==length):
        print(0)

Input:

In:Packed,InTransit,Packed,Shipped,Out-For-Delivery,Shipped,Delivered
In:Packed

Output:

1
3

Issue: Code is not printing 0 if the string is not found to compare the string otherwise I am getting desired output. Any help is much appreciated as I am very new in learning Python or a programming language.

You should move i = i + 1 outside of the condition.

Maybe you wanted to write not cargo_status in list .

Anyway it's not efficient. Here is an option:

statuses = str(input()).split(',')
query = str(input())

positions = [i for i, status in enumerate(statuses) if status == query]

for i in positions:
  print(i + 1)

if not positions:
  print('not found')

Can use enumerate and split here

s = 'Packed,InTransit,Packed,Shipped,Out-For-Delivery,Shipped,Delivered'
search = 'Packed'

print(*[idx if search in item else 0 for idx, item in enumerate(s.split(','), start = 1)])
 1 0 3 0 0 0 0

Expanded Loop

for idx, item in enumerate(s.split(','), start = 1):
    if search in item:
        print(idx)
    else:
        print(0)
 1 0 3 0 0 0 0

With regular Python, you can use enumerate with an if / else clause.

An interesting alternative, if you are happy to use a 3rd party library, is possible via NumPy and Boolean indexing:

import numpy as np

L = np.array(s.split(','))
A = np.arange(1, len(L)+1)
A[L != search] = 0

print(A)

array([1, 0, 3, 0, 0, 0, 0])

Here is a function that achieves the objective laid out in your question. However, Going through the effort of building a dictionary to query it only once would be quite wasteful, so use it if you would be querying more often than you would read the comma_separate_string.

def find_position(comma_sep_string, lookup_keyword):
    d = dict()
    _list = comma_sep_string.split(',')
    for index, element in enumerate(_list,1):
        try:
            d[element].append(index)
        except KeyError:
            d[element] = [index]

    return d.get(lookup_keyword, 0)

Sample output:

In [11]: find_position("Python,Python,Java,Haskell", 'Python')                                                       
Out[11]: [1, 2]

In [12]: find_position("Python,Python,Java,Haskell", 'Pytho')                                                        
Out[12]: 0

Note: had missed the requirement of printing 0 in case of string not found. One way to achieve this could be via a defaultdict .

l = "Packed,InTransit,Packed,Shipped,Out-For-Delivery,Shipped,Delivered".split(',')
from collections import defaultdict                         
d = defaultdict(list)
for i,e in enumerate(l,1):
    d[e].append(i)

sample run of above script on ipython:

In [6]: d                                                                                                            
Out[6]: 
defaultdict(list,
        {'Packed': [0, 2],
         'InTransit': [1],
         'Shipped': [3, 5],
         'Out-For-Delivery': [4],
         'Delivered': [6]})


In [7]: d['Packed']                                                                                                  
Out[7]: [0, 2]

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