如何在Python

时间:2016-09-13 13:25:36

标签: python string list replace letter

我有一个txt文件,其中包含字母表中的所有字母,如下所示:

B'/ P>

C

等。

我还有一个只有3个字母的单词列表:

年龄

蝙蝠

等...

我想创建一个列表,打印出从第一个单词开始可能的所有组合:

我的测试程序如下所示:

allcombi=[]
s= list("ago")
the.list=[]
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
    for line in letters:
        letter = line.strip()
        s[0]=letter
        print(s)

现在我只更改了第一个字母,但我很难加入这些字母,因为它只是这样:

['a','g','o'] ['b','g','o'] ....

帮助:

  1. 将其打印为[''','bgo']而不是

  2. 不要只更改第一个字母,而是在索引0,1中一次更改一个字母,并在单词中一次更改一个字母。输出应为27 * 3行,['前','bgo',........,'agx',agy,'agz']

  3. 我稍后会在字典中搜索新列表中的所有项目,但我可以弄清楚自己只是这部分真的让我陷入困境。

7 个答案:

答案 0 :(得分:2)

这将生成给定单词的所有组合的列表:

from string import ascii_lowercase
word = "ago"
combos = []
for i in xrange(len(word)):
    for l in ascii_lowercase:
        combos.append( word[:i]+l+word[i+1:] )

答案 1 :(得分:0)

正如@ Farhan.K在评论中提到的那样,你要找的是一个字符串方法,它从一个可迭代创建一个新字符串:join

Join是一个字符串的方法,它连接一个包含字符串的iterable,其中包含原始字符串。例如,如果您有一个单词列表作为一个发送,您可以通过调用' '.join(listOfWords)将它们与一个空格分开来加入它们。在您的情况下,您有一个需要在没有任何分隔符的情况下加入的字符列表,因此您将空字符串作为分隔符传递:''.join(listOfChars)

答案 2 :(得分:0)

这里有列表理解

[b+'g'+e for b in alphabet for e in alphabet]

您可以使用其他列表理解来定义字母

alphabet=[chr(c) for c in range(ord('a'),ord('z')+1)]

或许比用char写的char短得多......

答案 3 :(得分:0)

你需要为初学者设置嵌套循环。当您掌握了实际尝试的内容时,就可以看到itertools包。

使用您提供的代码,您应该需要以下内容:

var tribe_event_tickets_plus = tribe_event_tickets_plus || {};
tribe_event_tickets_plus.meta = tribe_event_tickets_plus.meta || {};
tribe_event_tickets_plus.meta.event = tribe_event_tickets_plus.meta.event || {};

(function ( window, document, $, my ) {
    'use strict';

    /**
     * Initializes the meta functionality
     */
    my.init = function() {
        $( '.tribe-list' ).on( 'click', '.attendee-meta.toggle', function() {
            $( this )
                .toggleClass( 'on' )
                .siblings( '.attendee-meta-row' )
                .slideToggle();
        });

        this.$ticket_form = $( '.tribe-events-tickets' ).closest( '.cart' );

        this.$ticket_form
            .on( 'change', '.quantity input, .quantity select', this.event.quantity_changed )
            .on( 'keyup', '.quantity input', this.event.quantity_changed )
            .on( 'submit', this.event.handle_submission );

        this.$ticket_form.find( '.quantity input:not([type="hidden"]), .quantity select' ).each( function() {
            my.set_quantity( $( this ) );
        } );

        $( '.tribe-event-tickets-plus-meta-fields' ).on( 'keydown', '.tribe-tickets-meta-number input', this.event.limit_number_field_typing );
    };

    my.render_fields = function( ticket_id, num ) {
        var $row = $( '.tribe-event-tickets-plus-meta' ).filter( '[data-ticket-id="' + ticket_id + '"]' );
        var $template = $row.find( '.tribe-event-tickets-plus-meta-fields-tpl' );
        var $fields = $row.find( '.tribe-event-tickets-plus-meta-fields' );
        var template_html = $template.html();

        if ( ! my.has_meta_fields( ticket_id ) ) {
            return;
        }

        var current_count = $fields.find( '.tribe-event-tickets-plus-meta-attendee' ).length;
        var diff = 0;

        if ( current_count > num ) {
            diff = current_count - num;

            $fields.find( '.tribe-event-tickets-plus-meta-attendee:nth-last-child(-n+' + diff + ')' ).remove();
            return;
        }

        diff = num - current_count;

        var i = 0;
        for ( ; i < diff; i++ ) {
            var tweaked_template_html = template_html;
            tweaked_template_html = template_html.replace( /tribe-tickets-meta\[\]/g, 'tribe-tickets-meta[' + ticket_id + '][' + ( current_count + i + 1 ) + ']' );
            tweaked_template_html = tweaked_template_html.replace( /tribe-tickets-meta_([a-z0-9\-]+)_/g, 'tribe-tickets-meta_$1_' + ( current_count + i + 1 ) + '_' );
            $fields.append( tweaked_template_html );
        }
    };

    my.set_quantity = function( $field ) {
        var quantity = parseInt( $field.val(), 10 );
        var ticket_id = parseInt( $field.closest( 'td' ).data( 'product-id' ), 10 );
        var template_html = $( document.getElementById( 'tribe-event-tickets-plus-meta-fields-tpl-' + ticket_id ) ).html();

        if ( quantity && my.has_meta_fields( ticket_id ) ) {
            $field.closest( 'table' ).find( '.tribe-event-tickets-plus-meta[data-ticket-id="' + ticket_id +'"]' ).show();
        } else {
            $field.closest( 'table' ).find( '.tribe-event-tickets-plus-meta[data-ticket-id="' + ticket_id +'"]' ).hide();
        }

        my.render_fields( ticket_id, quantity );
    };

    my.has_meta_fields = function( ticket_id ) {
        var template_html = $( document.getElementById( 'tribe-event-tickets-plus-meta-fields-tpl-' + ticket_id ) ).html();
        return !! $( template_html ).find( '.tribe-tickets-meta' ).length;
    };

    /**
     * Validates the required fields for custom meta
     */
    my.validate_submission = function() {
        var is_valid = true;
        var $fields = $( '.tribe-tickets-meta-required' );

        $fields.each( function() {
            var $el = $( this );
            var val = '';

            if ( $el.is( '.tribe-tickets-meta-radio' ) || $el.is( '.tribe-tickets-meta-checkbox' ) ) {
                val = $el.find( 'input:checked' ).length ? 'checked' : '';
            } else {
                val = $el.find( 'input, select, textarea' ).val();
            }

            if ( 0 === val.length ) {
                is_valid = false;
            }
        } );

        return is_valid;
    };

    my.event.quantity_changed = function() {
        my.set_quantity( $( this ) );
    };

    /**
     * Ensure that only whole numbers can be entered into the number field
     */
    my.event.limit_number_field_typing = function( e ) {
        if (
            // Allow: backspace, delete, tab, escape, and enter
            $.inArray( e.keyCode, [ 46, 8, 9, 27, 13, 110 ] ) !== -1 ||
            // Allow: Ctrl+A, Command+A
            ( e.keyCode === 65 && ( e.ctrlKey === true || e.metaKey === true ) ) ||
            // Allow: Ctrl+C
            ( e.keyCode === 67 && e.ctrlKey === true ) ||
            // Allow: Ctrl+V
            ( e.keyCode === 86 && e.ctrlKey === true ) ||
            // Allow: Ctrl+X
            ( e.keyCode === 88 && e.ctrlKey === true ) ||
            // Allow: home, end, left, right, down, up
            ( e.keyCode >= 35 && e.keyCode <= 40 )
        ) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ( ( e.shiftKey || ( e.keyCode < 48 || e.keyCode > 57 ) ) && ( e.keyCode < 96 || e.keyCode > 105 ) ) {
            e.preventDefault();
        }
    };

    /**
     * Event to handle the submission action
     *
     * Validates required meta fields and stores meta data into cookies
     */
    my.event.handle_submission = function( e ) {
        if ( ! my.validate_submission() ) {
            e.preventDefault();
            var $form = $( this ).closest( 'form' );

            $form.addClass( 'tribe-event-tickets-plus-meta-missing-required' );

            $( 'html, body').animate({
                scrollTop: $form.offset().top
            }, 300 );
            return;
        }

        var $meta_groups = $( '.tribe-event-tickets-plus-meta' );

        $meta_groups.each( function() {
            var $group = $( this );
            var ticket_id = $group.data( 'ticket-id' );
            var $attendees = $group.find( '.tribe-event-tickets-plus-meta-attendee' );

            if ( ! $attendees.length ) {
                return;
            }

            var data = $attendees.find( 'input, select, textarea' ).serialize();

            var key = 'tribe-event-tickets-plus-meta-' + ticket_id;

            var current = $.cookie( key );

            current = current ? $.deparam( current ) : null;

            if ( current && current.hasOwnProperty( 'tribe-tickets-meta' ) ) {
                data = $.deparam( data );

                if (
                    current.hasOwnProperty( 'tribe-tickets-meta' )
                    && data.hasOwnProperty( 'tribe-tickets-meta' )
                    && 'undefined' !== typeof current['tribe-tickets-meta'][ ticket_id ]
                    && 'undefined' !== typeof data['tribe-tickets-meta'][ ticket_id ]
                ) {
                    data['tribe-tickets-meta'][ ticket_id ].forEach( function( el, index, collection ) {
                        current['tribe-tickets-meta'][ ticket_id ].push( el );
                    } );

                    data = $.param( current );
                }
            } else {
                $.removeCookie( key );
            }

            // $.param does some weird stuff when converting a non-0 indexed array
            data = data.replace( /(tribe-tickets-meta\%5B\%5D\=\&)+/, '' );

            // $.param does some weird stuff when converting a non-0 indexed array
            data = data.replace( new RegExp( '(tribe-tickets-meta\%5B' + ticket_id + '\%5D\%5B\%5D\=\&)+' ), '' );

            $.cookie( key, data, {
                expires: 1,
                path: '/'
            } );
        } );
    };

    $( function() {
        my.init();
    } );
} )( window, document, jQuery, tribe_event_tickets_plus.meta );

使用itertools,这就变成了:

s = list('ago')
the_list=[]
with open("alfabeth.txt", "r", encoding = "utf-8") as letters:
    lines = [line for line in letters]

for i in range(len(s)):
    for ii in lines:
        tmp_s = list(s)
        tmp_s[i] = ii
        print(''.join(tmp_s))

答案 4 :(得分:0)

我明白了!有一个整洁的while循环。太自豪了。无论如何在这里发帖答案。

    allakombi=[]
s= list("söt")#startord
characters=[]
with open("alfabetet.txt", "r", encoding = "utf-8") as bokstäver:
        for rad in bokstäver:
               bokstav = rad.strip()
               characters.append(bokstav)

k=0
while k<3:
       i=0
       while i <len(characters):
              s= list("söt")
              s[k]=characters[i]
              i=i+1
              s="".join(s)
              allakombi.append(s)
       k=k+1


print(allakombi)

答案 5 :(得分:0)

作为示例,您需要一些嵌套循环来获取组合:

from string import ascii_lowercase

words = ["ago"]
combs = []
for word in words:
    for i, letter in enumerate(word):
        for l in ascii_lowercase:
            tmp = list(word)
            tmp[i] = l
            combs.append("".join(tmp))

print combs



>>> ['ago', 'bgo', 'cgo', 'dgo', 'ego', 'fgo', 'ggo', 'hgo', 'igo', 'jgo', 'kgo', 'lgo', 'mgo', 'ngo', 'ogo', 'pgo', 'qgo', 'rgo', 'sgo', 'tgo', 'ugo', 'vgo', 'wgo', 'xgo', 'ygo', 'zgo', 'aao', 'abo', 'aco', 'ado', 'aeo', 'afo', 'ago', 'aho', 'aio', 'ajo', 'ako', 'alo', 'amo', 'ano', 'aoo', 'apo', 'aqo', 'aro', 'aso', 'ato', 'auo', 'avo', 'awo', 'axo', 'ayo', 'azo', 'aga', 'agb', 'agc', 'agd', 'age', 'agf', 'agg', 'agh', 'agi', 'agj', 'agk', 'agl', 'agm', 'agn', 'ago', 'agp', 'agq', 'agr', 'ags', 'agt', 'agu', 'agv', 'agw', 'agx', 'agy', 'agz']

答案 6 :(得分:0)

您可以尝试以下方式:

letter=["ago"]

from string import ascii_lowercase

for i in ascii_lowercase:
    print(i+letter[0][1:])
    print(letter[0][:1]+i+letter[0][2:])
    print(letter[0][:2]+i)