简体   繁体   English

如何从带有特定项目的输入中打印列表

[英]How to print list from input with specific items

How to print list with from input with specific items? 如何从特定项目的输入中打印列表? For example with names which ends with x. 例如,名称以x结尾。 I've got this code 我有这个代码

while True:
    name = input("Enter your name: ")
    if name == "":
        break
    list = []
    namex = name.endswith("x")
    if name == namex:
        list.append(name)
    print (list)

but when i try to print list it gives me nothing: 但是当我尝试打印列表时,它什么也没有给我:

>>> Enter your name: alex
    Enter your name: james
    Enter your name: abcx
    Enter your name: 
>>>

Your issue is that namex is a boolean , not a string . 您的问题是namex是布尔值 ,而不是字符串

>>> 'abc'.endswith("x")
False
>>> 'abcx'.endswith("x")
True

This means that any equality comparison between a string and a boolean will return false. 这意味着字符串和布尔值之间的任何相等比较将返回false。 You want to trigger the "if" statement if the statement ends with "x", or: 如果语句以“ x”结尾,则要触发“ if”语句,或者:

names = []
while True:
    name = input("Enter your name: ")
    if name == "":
        break
    namex = name.endswith("x")
    # namex is a boolean type, which if it is True, will trigger an if statement
    if namex:
        names.append(name)
print(names)
namex = name.endswith("x")
if name == namex:

Does not do what you think it does. 不执行您认为的操作。 name.endswith("x") returns True or False . name.endswith("x")返回TrueFalse Should be 应该

if name.endswith("x"):

instead. 代替。

names = []
while True:
    name = input("Enter your name: ")
    if name == "":
        break
    if name.endswith("x"):
        names.append(name)
print (names)

List comprehension iter version: 列表理解iter版本:

>>> [name for name in iter(input, '') if name.endswith('x')]
dsf
sdfdsf
dsffdx
sx

['dsffdx', 'sx']

Here, I am storing all the names ending with 'x' in namex_list instead of using the list (also a built-in variable) variable you used before. 在这里,我将所有以“ x”结尾的名称存储在namex_list而不是使用之前使用的list (也是一个内置变量)变量。

Also, i am assigning namex_list as an empty list before the while condition and printing the namex_list at the end outside of while . 另外,我分配namex_list作为while条件之前的空单并打印namex_list末之外while

namex_list = []
while True:
    name = input("Enter your name: ")
    if name == "":
        break     
    if name.endswith("x"):
        namex_list.append(name)
print (namex_list)

Also, name == namex does not check what you are trying to achieve because of the comparison between string values and boolean values. 另外,由于字符串值和布尔值之间的比较,因此name == namex不会检查您要实现的目标。

For example: 例如:

>>> name1 = 'abc'
>>> name2 = 'abcx'
>>> namex1 = name1.endswith('x')
>>> namex2 = name2.endswith('x')

>>> namex1
False
>>> namex2
True

>>> name1 == namex1    
False
>>> name2 == namex2
False

You should use an if instead to achieve what you are trying to achieve in your code above: 您应该使用if来实现上面代码中要实现的目标:

if name.endswith("x"):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM