如何在python列表中查找特定字符串,如果找到,则打印位置,否则打印0

如何在python列表中查找特定字符串,如果找到,则打印位置,否则打印0,python,string,python-3.x,Python,String,Python 3.x,输入: 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

输入:

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)
输出:

In:Packed,InTransit,Packed,Shipped,Out-For-Delivery,Shipped,Delivered
In:Packed
问题:如果未找到用于比较字符串的字符串,则代码未打印0,否则我将获得所需的输出。
非常感谢您的帮助,因为我对学习Python或编程语言非常陌生。

您应该将
I=I+1
移到条件之外

也许你想写
而不是列表中的货物状态

不管怎样,这是没有效率的。这里有一个选项:

1
3
可以在此处使用枚举和拆分

扩展回路

1 0 3 0 0 0 0

对于常规Python,您可以将
enumerate
if
/
else
子句一起使用

如果您愿意使用第三方库,可以通过NumPy和布尔索引进行有趣的选择:

1
0
3
0
0
0
0

这里有一个函数可以实现问题中列出的目标。 但是,构建一个字典只查询一次是非常浪费的,因此如果您要比读取逗号分隔字符串更频繁地进行查询,请使用它

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])
样本输出:

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)

注意:如果未找到字符串,则未满足打印
0
的要求。 实现这一目标的一种方法是通过

在ipython上运行上述脚本的示例:

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)

你的elif状态有点不对劲。您将i与长度进行比较,但忘记了为每个循环增加i。若要解决此问题,请将i=i+1移到if-else语句之后,移到它们之外。0是python列表中的第一个索引,因此您可能希望打印未找到状态的
-1
numpy.NaN
None
,而不是0。然后,可能会返回0找到的项目的有效列表索引。请不要调用您的列表
list
。这将隐藏内置的
列表
类型。代码不错。谢谢你为新程序员扩展你的it。
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])
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)
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
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)
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]