python 如何从控制台读取输入行到多值列表中?

nsc4cvqm  于 2023-01-08  发布在  Python
关注(0)|答案(5)|浏览(158)

代码

我想输入多个值(见下面的注解行),这样用户就可以很容易地搜索多个值,并且循环可以找到这些值。
我怎样才能改变输入到一个文本列表,使程序检查一切?像这样:what_to_look = ['james','tom'].split()每行1怎么样-当从file.txt读取它时?我想我得到了一个错误的结果,post_id是帖子URL的实际id。我想知道在file.txt中列出他们名字的特定帖子py的id是否以及是什么。5和9但不是5和6。

title = ['james','tom','kim']
post_ids = [5,6,9]
what_to_look = input('Enter Name: ')   # convert this like (what_to_look = ['james','tom'] )

# search for the values
if what_to_look in title:
    position = title.index(what_to_look)
    post_id = post_ids[position]
    print('found', post_id)
else:
    print('not found')

如何将输入转换为类似('james','kim')的列表?

ni65a41a

ni65a41a1#

使用split()并迭代拆分的what_to_look输入,如果它在title列表中,则获取其索引:

title = ['james','tom','kim']
post_ids = [5,6,9]

what_to_look = input('Enter Name: ').split()

for name in what_to_look:
    if name in title:
        post_id = post_ids[title.index(name)]
        print('Found', post_id)
    else:
        print('Not found')

输出:

Enter Name: james tom
Found 5
Found 6

Enter Name: tom jerry
Found 5
Not found
siotufzp

siotufzp2#

下面是一个demo on IdeOne to try

titles = ['james','tom','kim']
locations = [5,6,9]

find_str = input('Find Names (separated by space): ') 
terms = find_str.split()   # split entered string by delimiter space into a list

print('Searching for terms:', terms)
for t in terms:  # loop through each given name and search it in titles
  if t.lower() in titles:  # compare lower-case, if found inside titles
    i = titles.index(t.lower())  # find position which is index for other list 
    loc = locations[i]  # use found position to get location number or URL
    print("Found given term:", t, "on index:", i, " has location:", loc)

我的输入(3个术语,以空格分隔):

James t. kirk

控制台输出(包括输入行):

Find Names (separated by space): James t. kirk
Searching for terms: ['James', 't.', 'kirk']
Found given term: James on index: 0  has location: 5
ztyzrc3y

ztyzrc3y3#

Python字符串提供了.split函数,该函数根据指定的分隔符将字符串分解为一个列表。
例如,names = what_to_look.split(" ")将在每个空格处打断what_to_look
为便于进一步参考,这里有一个指向文档拆分的链接

sy5wg1nm

sy5wg1nm4#

我认为您希望将值列表作为输入,可以使用以下代码输入它,例如

what_to_look = input().split()

然后你可以在单行中以空格分隔的文本输入值。希望对你有帮助!

qncylg1j

qncylg1j5#

您可以通过split()实现:

title = ['james','tom','kim']
post_ids = [5,6,9]
what_to_look = input('Enter Name: ')

可以将字符串值拆分到列表中;

entered_list = what_to_look.split()

这将从输入的字符串创建一个列表。
编辑:建议您按照@hc_dev的建议使用分隔符作为输入值。这将创建更好的用户体验并获得更好的搜索结果。

相关问题