我该怎么做才能解决这个问题并打印出以相同的第一个字母开头的元组中的所有名称

时间:2014-11-15 21:43:32

标签: python

boys=("david","andrew","ted","tom","james","nicholas","kyle","michael","mark")

startn=()
uname=raw_input("What is your first name?: ")
begin=uname[0]
for name2 in range(len(boys)):
     if begin== boys[name[0]]:
          startn+=(boys[name2],)
          print startn,"start with",begin

     else:
          print "Sorry there are no names that begin with", begin

3 个答案:

答案 0 :(得分:0)

您在访问name[0]时使用boys作为索引。您想要使用name2

if begin == boys[name2][0]:
    startn += boys[name2]

或者,您可以遍历boys数组本身:

for boy_name in boys:
    boy_name[0] == begin:
        startn += boy_name

(我不完全确定您使用startn做了什么,因为您还没有包含您的代码。)

答案 1 :(得分:0)

作为此目标的pythonic方式使用str.startswith()

>>> boys=("david","andrew","ted","tom","james","nicholas","kyle","michael","mark")
>>> boys[1].startswith('a')
True
>>> boys[2].startswith('b')
False

所以你的代码必须是:

boys=("david","andrew","ted","tom","james","nicholas","kyle","michael","mark")

startn=()
uname=raw_input("What is your first name?: ")
for name2 in boys:
     if name2.startswith(uname[0]):
          startn+=(boys[name2],)
          print startn,"start with",begin

     else:
          print "Sorry there are no names that begin with", begin

答案 2 :(得分:0)

你可以在这里改进一些事情。让我们看看我们如何清理它并使其正常工作。

for name2 in range(len(boys)):

您不需要range()len()来电。如果要迭代名称,可以直接使用for循环执行此操作。

for name in boys:

现在你的循环中有两个变量。您输入的名称为uname,循环name中的当前名称。您可以通过比较uname[0]name[0]

轻松比较每个字符的首字母