【问题标题】:array as position argument数组作为位置参数
【发布时间】:2019-03-29 08:16:54
【问题描述】:
try:
    target = int(input("Please enter the ammount you are looking for :"))
except ValueError:
    print("wrong value please enter a number")
    target = int(input("Please enter the ammount you are looking for :"))
found = False
location = [] # I want to use this list as position argument for another array passed from another function. is it possible?


for pos in range(0, len(wydatki)):
    if wydatki[pos] == target:
        found=True
        location.append(pos)

if found==True:
    #prints the locations in the list that the target was found
    print (target,"\nappears in the following locations: ",months[location])
else:
    print (target,"\nwas not found in the list.")

months[location]

通常你只能使用单个变量来指向数组中的位置?

【问题讨论】:

  • 我无法理解您的问题。您希望能够使用列表中的索引打印数组中项目的位置吗?就像如果你有一个列表a = ['apple', 'banana', 'carrot'] 和另一个索引列表b = [0, 2],你会得到apple, carrot

标签: python arrays list arguments python-3.7


【解决方案1】:

正如您所注意到的,您不能传递一个列表并将其用作索引。

您必须遍历每个索引,或者构建一个完整的字符串并打印出来。

例如

print(target,"\nappears in the following locations: ", end="")
for index in location:
    print(months[index], end=" ")
print("")

end="" 表示 print 将在末尾添加一个空字符串,而不是通常的新行。

此外,您还可以通过其他两种方式改进您的代码。

布尔值found 可以对应于列表location,其中包含任何值,所以

if location: # an empty list evaluates to False
  print("Found")
else:
  print("Not found")

您的输入可能看起来像这样

target = None
done = False
while not done:
  try:
    target = int( input("Please enter the amount you are looking for:") )
    done = True
  except ValueError:
    print("Wrong value, input a number.")

因此用户可以多次失败,程序将无法继续。

【讨论】:

    【解决方案2】:

    如果你稍微改变一下你的输出,你可以:

    target = 42
    location = []
    # 42 occures at positions 3,6,8
    #           0 1 2 3  4 5 6  7 8  9
    wydatki = [ 1,2,3,42,4,5,42,6,42,8]
    
    #         pos: 01234567890
    months = list("abcdefghijk")
    
    # get the positions unsing enumerate
    for pos,value in enumerate(wydatki):
        if value == target:
            location.append(pos)
    
    if location: # empty lists are False, lists with elements are True
        #prints the locations in the list that the target was found
        print (target,"\nappears in the following locations: ", 
               ','.join( (months[a] for a in location) ) )
    else:
        print (target,"\nwas not found in the list.")
    

    输出:

    42 
    appears in the following locations:  d,g,i
    

    基本上,您需要将所有月份条目插入并加入一个字符串 - f.e.在","join( ... ) 语句中使用生成器表达式。

    【讨论】:

    • 快速提问 Patrick 为什么将 for pos in range(0, len(wydatki)): 更改为 : for pos,value in enumerate(wydatki): 只是让代码更高效吗?还是有其他用途?
    • @ChefJ:因为这样做感觉很笨拙。如果我在迭代一个可迭代对象时需要位置,我使用enumerate(iterable) 这给了我位置和值,而无需将索引返回到我的可迭代对象中。 found=True 也一样 - 它根本不需要 - 你声明一个变量来捕获是否将某些东西放入 location - 你可以简单地使用 location 本身 - 如果其中有任何东西,它是 True,否则它是False:见truth-value-testing
    • 感谢它刚刚开始使用 python 5 周,所以一切都是新的。
    • @ChefJ 如果您还想了解输入验证,请阅读Asking user for input until they give a valid response - 如果您是新手,您可能需要转到 [python] 选项卡并切换到 Votes (stackoverflow.com/questions/tagged/…) - 前 100 条左右的内容非常适合阅读注意事项 - python-3.x 标签也是如此:stackoverflow.com/questions/tagged/… - 它们是排名最高的问答主题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多