如何在字符串列表中搜索变量

时间:2017-04-28 16:19:47

标签: python

我有非常基本的python知识。到目前为止这是我的代码: 当我运行此代码时,显示错误response = [str(input("Would you rather eat an apple or an orange? Answer apple or orange."))] list1 =[str("apple"), str("Apple"), str("APPLE")] lsit3 = [str("an orange"), str("Orange"), str("orange"), str("an Orange"), str("ORANGE")] def listCompare(): for list1[0] in list1: for response[0] in response: if response[0] == list1[0]: response = true else: for list3[0] in list3: for response[0] in response: if response[0] == list3[0]: response = false listCompare() 。我正在尝试创建一个函数,将响应输入与两个列表进行比较,如果找到该输入,则将true或false分配给响应。我还需要将响应分配给另一个答案列表,该响应应该是真或假。 (将为真或假分配值,并计算答案列表的总和以匹配最终列表计算。)

TreeMap <String, List<String>> department = new TreeMap<>();
department.put("AB", Arrays.asList("Bob", "Truus", "Miep"));
department.put("CD", Arrays.asList("Jan", "Kees", "Huub"));
department.put("EF", Arrays.asList("Jan", "Piet", "Bert"));
String aValue = "Jan";

Map<String,List<String>> result = department.entrySet().stream()
// filter out those departments that don't contain aValue
  .filter(entry -> entry.getValue().contains(aValue))
// collect the matching departments back into a map 
  .collect(Collectors.toMap(k -> k.getKey(), k -> k.getValue()));

// print the result
result.forEach((k,v)-> System.out.println(k + " " + v.toString()));

**编辑:好的。谢谢你的烤肉。我在高中,在一个非常基础的课程中途。我只是想让这项工作通过。我不需要&#34;帮助&#34;了。

2 个答案:

答案 0 :(得分:2)

这里的事情很复杂,但如果你不熟悉编程或python,这是可以理解的。

为了让您走上正轨,这是解决问题的更好方法:

valid_responses = ['a', 'b']
response = input("chose a or b: ").lower().strip()
if response in valid_responses:
    print("Valid response:", response)
else:
    print("Invalid response:", response)

在这里查找您不理解的任何功能。

字符串声明也可以是单引号或双引号:

my_strings = ['orange', "apple"]

另外,要在函数内部分配全局变量,需要使用global关键字。

my_global = "hello"

def my_fuction():
    global my_global
    # Do stuff with my_global

For循环应该分配给新的局部变量:

options = ['a', 'b', 'c']

for opt in options:
    print(opt)

答案 1 :(得分:0)

您可以改为匹配可能答案的模式,而不是枚举确切可能答案的列表。这是一种方法,不区分大小写:

import re

known_fruits = ['apple', 'orange']
response = str(input("What would you like to eat? (Answer " + ' or '.join(known_fruits) + '): '))

def listCompare():
    for fruit in known_fruits:
        pattern = '^(?:an\s)?\s*' + fruit + '\s*$'
        if re.search(pattern,response,re.IGNORECASE):
            return True

if listCompare():
    print("Enjoy it!")
else:
    print("'%s' is an invalid choice" % response)

这将匹配appleApple甚至ApPle。它也会匹配'一个苹果'。但是,它与pineapple不匹配。

这是相同的代码,正则表达式细分:

import re

known_fruits = ['apple', 'orange']

print("What would you like to eat?")

response = str(input("(Answer " + ' or '.join(known_fruits) + '): '))

# Change to lowercase and remove leading/trailing whitespace
response = response.lower().strip()

def listCompare():
    for fruit in known_fruits:
        pattern = (
                  '^'     + # Beginning of string
                  '('     + # Start of group
                    'an'  + #    word "an"
                    '\s'  + #    single space character
                  ')'     + # End of group
                  '?'     + # Make group optional
                  '\s*'   + # Zero or more space characters
                  fruit   + # Word inside "fruit" variable
                  '\s*'   + # Zero or more space characters
                  '$'       # End of the string
                  )
        if re.search(pattern,response):
            return True

if listCompare():
    print("Enjoy it!")
else:
    print("'%s' is an invalid choice" % response)